Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Subscribe to see which companies asked this question
class Solution {
public:
bool judge(TreeNode *p,TreeNode *q)
{
if(!p&&!q)return true;
else if(p&&q&&p->val==q->val) return judge(p->left,q->right)&&judge(p->right,q->left);
else return false;
}
bool isSymmetric(TreeNode* root) {
if(!root)return true;
else return judge(root->left,root->right);
}
};
非递归:<pre name="code" class="cpp">class Solution {
public:
bool isSymmetric(TreeNode *root) {
if (!root) return true;
queue<TreeNode*> q1, q2;
q1.push(root->left);
q2.push(root->right);
while (!q1.empty() && !q2.empty())
{
TreeNode *t1 = q1.front();
TreeNode *t2 = q2.front();
q1.pop();
q2.pop();
if (!t1 && !t2) continue;
if (!t1|| !t2) return false;
if(t1->val!=t2->val) return false;
q1.push(t1->left);
q1.push(t1->right);
q2.push(t2->right);
q2.push(t2->left);
}
return true;
}
};