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
Note:
Bonus points if you could solve it both recursively and iteratively.
Analysis:
1. Recursive method. If a tree is symmetric, its left and right sub-trees are mirrored symmetrically. For judging whether the two trees are mirrored symmetrical, if the root node values of the two trees are the same, and the left child of tree A is mirrored symmetrical with the right child of tree B and the right side of tree A is mirrored symmetrically to the left of tree B, then the tree A and B are mirrored symmetrically. The code is as follows:
1 classSolution {2 Public:3 BOOLIssymmetric (TreeNode *root) {4 if(Root = NULL)return true;5 returnIs_mirror (Root->left, root->Right );6 }7 BOOLIs_mirror (TreeNode *l, TreeNode *R) {8 if(L = = NULL | | r = = NULL)returnL = =R;9 if(L->val! = r->val)return false;Ten returnIs_mirror (L->left, R->right) && is_mirror (L->right, r->Left ); One } A};
Iterative algorithm is a variant of the iterative traversal algorithm using the stack tree. The main idea is to push the symmetric two nodes to the stack at the same time, and then each time from the top of the stack pop two to determine whether the same. The code is as follows:
classSolution { Public: BOOLIssymmetric (TreeNode *root) { if(Root = NULL)return true; Stack<treenode *>s; S.push (Root-Left ); S.push (Root-Right ); while(!S.empty ()) {TreeNode*r =s.top (); S.pop (); TreeNode*l =s.top (); S.pop (); if(r = = NULL && L = = null)Continue;//This is very import if(r = = NULL | | l = = NULL)return false; if(R->val! = l->val)return false; S.push (R-Left ); S.push (L-Right ); S.push (R-Right ); S.push (L-Left ); } return true; }};
Leetcode:symmetric Tree