实现一个函数,用来判断一棵二叉树是不是对称的.
例如,二叉树 [1,3,3,4,5,5,4] 是对称的。
1
/ \
3 3
/ \ / \
4 5 5 4
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int MirrorImage(struct TreeNode* root_left, struct TreeNode* root_right)
{
if(!root_right&&!root_left)
return 1;
if(!root_right||!root_left)
return 0;
if(root_left->val!=root_right->val)
return 0;
int left = MirrorImage(root_left->left, root_right->right);
if(left==0) return 0;
int right = MirrorImage(root_left->right ,root_right->left);
if(right==0) return 0;
return 1;
}
bool isSymmetric(struct TreeNode* root){
if(root){
return MirrorImage(root->left, root->right) ? true : false;
}else{
return true;
}
}