Problem
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:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following[1,2,2,null,3,null,3]is not:
1
/ \
2 2
\ \
3 3
思路
- 看当前这颗树是否对称,需要看,他的左子树和右子树是否对称
- 所以创建一个函数检测给定的两个树是否对称
- 根节点的值必须相同
- A左和B右相同, A右和B左相同
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode left, TreeNode right) {
if (left == null || right == null) {
return left == right;
}
if (left.val != right.val) return false;
return isSymmetric(left.left, right.right) && isSymmtric(left.right, right.left);
}
stack 版本
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
TreeNode l = root.left;
TreeNode r = root.right;
if (l == null && r == null) return true;
Stack<TreeNode> stack = new Stack<>();
if (l != null && r != null && l.val == r.val) {
stack.push(l);
stack.push(r);
} else return false;
while (!stack.isEmpty()) {
if (stack.size() % 2 != 0) return false;
TreeNode right = stack.pop();
TreeNode left = stack.pop();
if (left.val != right.val) return false;
if (left.left != null) {
if (right.right == null) return false;
stack.push(left.left);
stack.push(right.right);
} else if (right.right != null) {
return false;
}
if (left.right != null) {
if (right.left == null) return false;
stack.push(left.right);
stack.push(right.left);
} else if (right.left != null) {
return false;
}
}
return true;
}