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.
1. Recursion
bool issymmetric (TreeNode *p, TreeNode *q) { ifreturntrue; if return false ; return (P->val = = q->val) && issymmetric (P->left, q->right) && Issymmetric (P->right, q-> left);}
2. Non-recursive
BOOLIssymmetric (TreeNode *p, TreeNode *P) {Queue<TreeNode*>Q1; Queue<TreeNode*>Q2; Q1.push (P); Q2.push (q); while(Q1.size () >0&& q2.size () >0) {TreeNode* P1 =Q1.front (); Q1.pop (); TreeNode* P2 =Q2.front (); Q2.pop (); if(P1==null && P2==null)Continue; if(P1==null | | p2==null)return false; if(P1->val! = p2->val)return false; Q1.push (P1-Left ); Q2.push (P2-Right ); Q1.push (P1-Right ); Q2.push (P2-Left ); } return true;}
101. Symmetric Tree--judging whether the structure of trees is symmetrical