Description
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Examples
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
思路
有两种方法
- 用bfs,比较每一行是否中心对成
- 用递归,比较 right.left & left.right 以及 right.right & left.left
代码
bfs
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
List<TreeNode> left = new ArrayList<>();
List<TreeNode> right = new ArrayList<>();
left.add(root.left);
right.add(root.right);
while (left.size() > 0 && right.size() > 0){
List<TreeNode> newLeft = new ArrayList<>();
List<TreeNode> newRight = new ArrayList<>();
if (left.size() != right.size())
return false;
for(int i = 0; i < left.size(); i++){
if (left.get(i) == null || right.get(left.size() - 1 - i) == null){
if (left.get(i) == null && right.get(left.size() - 1 - i) == null){
left.remove(i);
right.remove(right.size() - 1 - i);
i--;
continue;
}
return false;
}
if (left.get(i).val != right.get(right.size() - 1 - i).val)
return false;
}
for (int i = 0; i < left.size(); i++){
newLeft.add(left.get(i).left);
newLeft.add(left.get(i).right);
newRight.add(right.get(i).left);
newRight.add(right.get(i).right);
}
left = new ArrayList<>(newLeft);
right= new ArrayList<>(newRight);
}
return true;
}
}
递归
class Solution {
public boolean isSymmetric(TreeNode root) {
// corner case
if (root == null) return true;
return isSymmetric(root, root);
}
private boolean isSymmetric(TreeNode left, TreeNode right) {
if (left != null && right != null) {
return (left.val == right.val ) && isSymmetric(left.right,right.left) && isSymmetric(right.left, left.right);
} else if (left == null && right == null) {
return true;
} else {
return false;
}
}
}