给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/
2 2
/ \ /
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/
2 2
\
3 3
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
/**
* 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) {
if(root == NULL)
return true;
queue<TreeNode*> q;
q.push(root);
q.push(root);
while( !q.empty() ){
TreeNode* node1 = q.front();
q.pop();
TreeNode* node2 = q.front();
q.pop();
if(node1 == NULL && node2 == NULL)
continue;
if(node1 == NULL || node2 == NULL)
return false;
if(node1->val != node2->val)
return false;
q.push(node1->left);
q.push(node2->right);
q.push(node1->right);
q.push(node2->left);
}
return true;
}
};
*/
//递归
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL)
return true;
return ismirror(root, root);
}
private:
bool ismirror(TreeNode* root1, TreeNode* root2){
if(root1 == NULL && root2 == NULL)
return true;
if(root1 == NULL || root2 == NULL)
return false;
if(root1->val != root2->val)
return false;
return ismirror(root1->left, root2->right) && ismirror(root1->right, root2->left);
}
};