题解 | #判断是不是平衡二叉树#

判断是不是平衡二叉树

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

思路

使用递归的方法计算平衡二叉树的左右子树最大深度,在递归的每一层我们都判断一下当前节点的左右子树深度是否符合平衡二叉树条件,如果符合,返回最大深度,反之直接返回-1,

代码

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        // 空树属于平衡二叉树
        if (root == null) {
            return true;
        }
        // 默认根节点深度为0
        // 创建变量接收返回最大深度
        int leftDepth = BinaryTreeDepth(root.left, 1);
        int rightDepth = BinaryTreeDepth(root.right, 1);
        // 判断子树中是否存在不满足平衡二叉树条件的情况
        if (leftDepth == -1 || rightDepth == -1) {
            return false;
        }
        // 返回最终结果
        return Math.abs(leftDepth - rightDepth) <= 1;
    }

    /**
     * 计算传入平衡二叉树的最大深度
     *
     * @param root  根节点
     * @param depth 当前深度
     * @return int
     * @apiNote 在计算深度的同时会判断本层节点是否符合平衡二叉树的条件,如果满足返回最大深度,反之返回-1
     * @since 2023/1/3 14:37
     */
    public int BinaryTreeDepth(TreeNode root, int depth) {
        // 如果传入的节点为空节点,说明到达最底层了直接返回传入深度
        if (root == null) {
            return depth;
        }
        // 如果深度为-1,直接返回
        if (depth == -1) {
            return depth;
        }
        // 当前深度自增
        depth++;
        // 创建变量接收返回最大深度
        int leftDepth = BinaryTreeDepth(root.left, depth);
        int rightDepth = BinaryTreeDepth(root.right, depth);
        // 判断当前节点是否符合平衡二叉树条件
        if (Math.abs(leftDepth - rightDepth) > 1) {
            // 不满足返回-1
            return -1;
        } else {
            // 满足条件返回最大深度
            return Math.max(leftDepth, rightDepth);
        }
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 15:39
希望奇迹发生的布莱克...:真的是 现在卷实习就是没苦硬吃
点赞 评论 收藏
分享
找个工作&nbsp;学历是要卡的&nbsp;要求是高的&nbsp;技能不足是真的&nbsp;实习经验是0的&nbsp;简历无处可写是事实的&nbsp;钱不好赚是真的&nbsp;想躺平又不敢躺&nbsp;也不甘心躺&nbsp;怕自己的灵感和才华被掩埋甚至从未被自己发现&nbsp;又质疑自己是否真正有才华
码农索隆:你现在啊,你心里都明白咋回事,但是你没办法改变现状,一想到未来,你又没有信心狠下心来在当下努力。 得走出这种状态,不能一直困在那里面,哪不行就去提升哪,你一动不动那指定改变不了未来,动起来,积少成多才能越来越好
点赞 评论 收藏
分享
05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务