28. 对称的二叉树
题目描述
判断一棵二叉树是不是对称的,也就是它和它的镜像是否相同。
解题思路
一棵树对称,等价于根的左右子树互为镜像。比较两棵子树 t1 和 t2 是否互为镜像:根的值相同,并且 t1 的左子树与 t2 的右子树互为镜像、t1 的右子树与 t2 的左子树互为镜像。
public boolean checkSymmetricTree(TreeNode root) {
if (root == null)
return true;
return checkSymmetricTree(root.left, root.right);
}
private boolean checkSymmetricTree(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null)
return true;
if (t1 == null || t2 == null)
return false;
if (t1.val != t2.val)
return false;
return checkSymmetricTree(t1.left, t2.right) && checkSymmetricTree(t1.right, t2.left);
}