【剑指Offer】对称的二叉树

题目

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

实现

1
2
3
4
5
6
7
8
9
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public boolean isSymmetrical(TreeNode pRoot) {
if (pRoot == null)
return true;

return isSymmetricalHelper(pRoot.left, pRoot.right);
}

private boolean isSymmetricalHelper(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 false;

return isSymmetricalHelper(left.left, right.right) && isSymmetricalHelper(left.right, right.left);
}