Given a binary tree, check whether it is a mirror of the itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / 2 2/\/3 4 4 3
But the following are not:
1 / 2 2 \ 3 3
Judging whether a tree is symmetrical, the first method of recursion is of course easier to solve:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A BOOLIssymmetric (treenode*root) { - if(Root = =NULL) - return true; the if(!root->left &&!root->Right ) - return true; - if(Root->left &&!root->right | |!root->left && root->Right ) - return false; + returnChecksymmetric (Root->left, root->Right ); - } + A BOOLChecksymmetric (TreeNode * left, TreeNode *Right ) at { - if(!left &&!)Right ) - return true; - if(!left && Right | | Left &&!Right ) - return false; - if(Left->val! = right->val) in return false; - returnChecksymmetric (Left->left, Right->right) && checksymmetric (Left->right, right->Left ); to } +};
The topic is also required to be implemented in a non-recursive manner, creating two queues that can be implemented:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A BOOLIssymmetric (treenode*root) { -Queue<treenode *>Q1; -Queue<treenode *>Q2; the if(Root = NULL)return true; - if(!root->left &&!root->right)return true; - if(Root->left &&!root->right | |!root->left && root->right)return false;//Val -Q1.push (root->Left ); +Q2.push (root->Right ); -TreeNode * Tmpleft, *Tmpright; + while(!q1.empty () &&!Q2.empty ()) { ATmpleft =Q1.front (); atTmpright =Q2.front (); - Q1.pop (), Q2.pop (); - if(!tmpleft &&!)tmpright) - Continue; - if(!tmpleft && tmpright | | tmpleft &&!tmpright) - return false; in if(Tmpleft->val! = tmpright->val) - return false; toQ1.push (tmpleft->Left ); +Q1.push (tmpleft->Right ); -Q2.push (tmpright->Right ); theQ2.push (tmpright->Left ); * } $ returnQ1.empty () &&q2.empty ();Panax Notoginseng } -};
Leetcode oj:symmetric tree tree (symmetrical trees)