剑指offer-58.对称的二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 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);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zxm1306192988/article/details/82017559