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.
Idea: To wait until the left son and the right son of the results are known, can judge the current node symmetry, so is the post-order traversal
Method I: Recursive sequential traversal
classSolution { Public: BOOLIssymmetric (TreeNode *root) { if(!root)return true; BOOLresult; if((root->left==null && root->right! = NULL) | | (root->left!=null && Root->right = =NULL)) { return false; } Else if(Root->left = = NULL && Root->right = =NULL) { return true; } Else{result= CMP (Root->left, root->Right ); } } BOOLCMP (TreeNode * Node1, treenode*Node2) { intRESULT1 =true; intRESULT2 =true; if(Node1->val!=node2->val)return false; Else { //Recursive end condition: at least one of the nodes is null if((node1->left==null && node2->right! = NULL) | |(Node1->left!=null && node2->right = NULL) | |(Node1->right!=null && node2->left = NULL) | |(Node1->right==null && Node2->left! =NULL)) { return false; } if((Node1->left = = NULL && Node2->right = = null) &&(Node1->right = = NULL && node2->left==NULL)) { return true; } //compare the two points to each other to compare the left son of node 1 and the right son of Node 2, as well as the right son of node 1 and the left son of Node 2 if(Node1->left! =NULL) {RESULT1= CMP (node1->left,node2->Right ); } if(Node1->right! =NULL) {RESULT2= CMP (node1->right,node2->Left ); } return(Result1 &&result2); } } };
Method II: Hierarchical Traversal with queues (hierarchy traversal is always implemented with queues)
classSolution { Public: BOOLIssymmetric (TreeNode *root) { if(Root = NULL)return true; Queue<TreeNode*>Q; Q.push (Root-Left ); Q.push (Root-Right ); TreeNode*T1, *T2; while(!Q.empty ()) {T1=Q.front (); Q.pop (); T2=Q.front (); Q.pop (); if(T1 = = NULL && T2 = =NULL)Continue; if(T1 = = NULL | | t2 = = NULL | | T1->val! = t2->val)return false; Q.push (T1-Left ); Q.push (T2-Right ); Q.push (T1-Right ); Q.push (T2-Left ); } return true; }};
101. Symmetric tree (tree, Queue; DFS, WFS)