给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
二叉树[1,2,2,null,3,3,null,5,-2,-2,5]是对称的。
1
/ \
2 2
\ /
3 3
/ \ / \
5 -2 -2 5
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return judge(root -> left, root -> right);
}
bool judge(TreeNode *l, TreeNode *r)
{
if(!l && !r) return true; // 如果既没有左子树也没有右子树,true
if(!l || !r) return false; // 如果有右没左或者有左没右,false
if(l -> val != r -> val) return false; // 如果左右都有,但是值不相等,false
return judge(l -> left, r -> right) && judge(l -> right, r -> left);
}
};