题目:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
思路:
把树分为左子树和右子树两个树进行递归。先比较两个数val是否相等,然后左子树指向下一个左子树,右子树指向下一个右子树。依次类推。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int emmm(struct TreeNode* r,struct TreeNode* l){
int Re;
if(r&&l){
if(r->val!=l->val)
return 0;
Re=emmm(l->left,r->right);
if(Re==0)
return 0;
Re=emmm(l->right,r->left);
if(Re==0)
return 0;
}else if(r==NULL&&l!=NULL||r!=NULL&&l==NULL)
return 0;
return 1;
}
bool isSymmetric(struct TreeNode* root){
if(root==NULL)
return 1;
int r=0;
r=emmm(root->right,root->left);
return r;
}
leetcode标准答案:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isMirror(struct TreeNode* root1, struct TreeNode* root2){
if(root1 == NULL && root2 == NULL) return true;
if(root1 == NULL || root2 == NULL) return false;
return (root1->val == root2->val) && isMirror(root1->left, root2->right) && isMirror(root1->right, root2->left);
}
bool isSymmetric(struct TreeNode* root){
return isMirror(root, root);
}