For example, this binary tree
[5,3,3,1,4,4,1]
is symmetric:
5
/ \
3 3
/ \ / \
1 4 4 1
or
5
/ \
3 3
/ \
1 1
public class SymmetricTree {
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;
if (left == null || right == null)
return false;
if (left.val != right.val)
return false;
return isSymmetric(left.left, right.right) &&
isSymmetric(left.right, right.left);
}
}