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:
Example:
[1,2,2,3,4,4,3]
true
[1,2,2,null,3,null,3]
false
Note:
Bonus points if you could solve it both recursively and iteratively.
解釋下題目:
判斷一棵樹是不是鏡像的
1. 遞歸1
實際耗時:12ms
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isMirror(root.left, root.right);
}
public boolean isMirror(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
} else if (left == null || right == null) {
return false;
} else {
if (left.val == right.val) {
return isMirror(left.left, right.right) && isMirror(left.right, right.left);
} else {
return false;
}
}
}
踩過的坑:空樹
??思路很簡單,直接看就行