Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
题意:判断一颗树是否是镜像对称的。
解法1:使用DFS
public boolean isSymmetric(TreeNode root) { if(root == null) return true; return isSymmetric(root.left, root.right); } public boolean isSymmetric(TreeNode left, TreeNode right) { if(left == null && right == null) return true; else if(left == null || right == null || left.val != right.val) return false; else return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); }
解法2:使用BFS
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
List<TreeNode> result = new ArrayList<TreeNode>();
result.add(root);
while (!result.isEmpty()) {
// check it is symmetric in same line
for (int i=0, j=result.size()-1; i < j; ) {
if (result.get(i) == null && result.get(j) == null) {
result.remove(j);
result.remove(i);
j = j-2;
} else if (result.get(i) == null || result.get(j) == null || result.get(i).val != result.get(j).val) {
return false;
} else {
i++;
j--;
}
}
// put next line in the list and remove all current line node
int length = result.size();
for (int i=0; i<length; i++) {
TreeNode currentNode = result.remove(0);
result.add(currentNode.left);
result.add(currentNode.right);
}
}
return true;
}