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

判断是不是平衡二叉树

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

package com.hhdd.数据结构.树;

/**
 * @Author huanghedidi
 * @Date 2022/8/24 23:35
 */
public class 判断是否平衡二叉树 {

    public boolean IsBalanced_Solution(TreeNode root) {
        int res = treeDepth(root);
        return res == -1 ? false : true;
    }

    public int treeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        /**
         * 求左子树深度
         */
        int l = treeDepth(root.left);
        // 返回 -1 则说明左子树已不是平衡二叉
        if (l == -1) {
            return -1;
        }
        int r = treeDepth(root.right);
        if (r == -1) {
            return -1;
        }
        if (Math.abs(l - r) > 1) {
            return -1;
        }
        return Math.max(l, r) + 1;
    }

}

全部评论

相关推荐

08-13 17:27
门头沟学院 Java
等闲_:还是那句话,这样只能海投,没有太多需要改的,因为大部分简历都是这样的,唯一可以把蓝桥杯三等奖放到最后
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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