版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxm1306192988/article/details/82017559
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
题解:
递归求解
分别比较左右子树
如果两个子树都为null ,则返回 true;
如果一个为空一个不为空,则返回 false;
如果两个子树的值不相等,则返回false;
否则分别比较,他们的左右子树,和右左子树,是否满足条件。
class Solution {
boolean isSymmetrical(TreeNode pRoot) {
if (pRoot == null) {
return true;
}
return check(pRoot.left, pRoot.right);
}
private boolean check(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) {
return true;
}
if ((t1 == null && t2 != null) || (t1 != null && t2 == null)) {
return false;
}
if (t1.val != t2.val) {
return false;
} else {
return check(t1.left, t2.right) && check(t1.right, t2.left);
}
}
}