Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
主要看树是否镜像对称
解法:
像数组对称一样,从外到中间,两两相同
边界:
树root为null时返回true
左右子树都为空时返回true
左右一个空一个不空false
左右value不同时false
然后递归:
比较left.left和right.right && left.right和right.left
public boolean isSymmetric(TreeNode root) {
if(root == null) {
return true;
}
return dfs(root.left, root.right);
}
public boolean dfs(TreeNode left, TreeNode right) {
if(left == null && right == null) {
return true;
}
if(left == null || right == null) {
return false;
}
if(left.val != right.val) {
return false;
}
return (dfs(left.left, right.right) && dfs(left.right, right.left));
}