对称二叉树
Category Difficulty Likes Dislikes
algorithms Easy (46.13%) 327 -
Tags
Companies
-
给定一个二叉树,检查它是否是镜像对称的。
-
例如,二叉树 [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 isSymmetric(TreeNode root) {
if (root == null)
return true;
return judge(root.left, root.right);
}
public static boolean judge(TreeNode a, TreeNode b) {
if (a == null || b == null)
return a == b ? true : false;
return a.val == b.val && judge(a.left, b.right) && judge(a.right, b.left);
}
}