Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
TreeNode *p,*q;
if(!root){
return true;
}
queue<TreeNode*> Q1,Q2;
Q1.push(root->left);
Q2.push(root->right);
while(!(Q1.empty())&&!(Q2.empty())){
p = Q1.front();
Q1.pop();
q = Q2.front();
Q2.pop();
if(p == NULL&& q == NULL)
continue;
else if(p == NULL|| q == NULL)
return false;
else if(p->val != q->val)
return false;
Q1.push(p->left);
Q1.push(p->right);
Q2.push(q->right);
Q2.push(q->left);
}
return true;
}
};