给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
代码:
class Solution {
public boolean compare(TreeNode left,TreeNode right) {
if(left == null && right == null)
return true;
else if ((left == null &&right != null)||(left != null&&right==null)) {
return false;
}
else if(left.val!=right.val) {
return false;
}
else {
return compare(left.left, right.right)&&compare(left.right, right.left);
}
}
public boolean isSymmetric(TreeNode root) {
TreeNode pNode = new TreeNode(0);
pNode = root;
if(pNode == null) {
return true;
}
TreeNode left = new TreeNode(0);
TreeNode right = new TreeNode(0);
left = root.left;
right = root.right;
return compare(left,right);
}
}