Check if a given binary tree is symmetric.
Examples
5
/ \
3 3
/ \ / \
1 4 4 1
is symmetric.
5
/ \
3 3
/ \ / \
1 4 1 4
is not symmetric.
Corner Cases
- What if the binary tree is null? Return true in this case.
Solution: 比较left和right,分为同null,其中一个null,同不null(分为val不同,val相同:比较左左和右右,左右和右左)
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return check(root.left, root.right);
}
private boolean check(TreeNode a, TreeNode b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
if (a.key != b.key) {
return false;
}
return check(a.left, b.right) && check(a.right, b.left);
}