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
This topic can be done in an iterative way, or it can be done in a recursive way. The first reaction to meeting the tree-related topics is recursion, so my solution is recursion.
The code:
classSolution { Public: BOOLIssymmetric (TreeNode *node1, TreeNode *Node2) { if(Node1 = = Null&&node2 = =NULL)return true; if(Node1 = = null| | Node2 = =NULL)return false; BOOLResult1, RESULT2; if(Node1->val! = node2->val)return false; Else{RESULT1= Issymmetric (Node1->left, node2->Right ); RESULT2= Issymmetric (Node1->right, node2->Left ); } returnresult1&&result2; } BOOLIssymmetric (TreeNode *root) { if(Root = NULL | | root->left = = Null&&root->right = =NULL)return true; BOOLresult = Issymmetric (Root->left, root->Right ); returnresult; } };
Looking at the solution of the relevant person, some people directly with the iterative way out, feeling very inspired
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: BOOLIssymmetric (TreeNode *root) { //Important:please Reset any member data declared, as//The same solution instance would be a reused for each test case. if(Root = NULL)return true; Queue<TreeNode*>Qleft, Qright; if(root->left) Qleft.push (root->Left ); if(root->right) Qright.push (root->Right ); while(Qleft.empty () = =false&& qright.empty () = =false) {TreeNode*QL =Qleft.front (); TreeNode*QR =Qright.front (); Qleft.pop (); Qright.pop (); if(Ql->val = = qr->val) { if(Ql->left && qr->Right ) {Qleft.push (QL-Left ); Qright.push (QR-Right ); } Else if(Ql->left | | qr->Right )return false; if(Qr->left && ql->Right ) {Qleft.push (QR-Left ); Qright.push (QL-Right ); } Else if(Qr->left | | ql->Right )return false; } Else return false; } if(Qleft.empty () &&qright.empty ())return true; Else return false; }};
Transfer from http://www.cnblogs.com/TenosDoIt/p/3440729.html
Happyleetcode43:symmetric Tree