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

判断是不是平衡二叉树

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

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        // 使用递归来完成
        // 比较左右子树的高度来判断是否为平衡二叉树
        // 所以定义一个计算二叉树高度的方法
        if(root == null ){
            return true;
        }
        // 计算左右子树的高度
        int leftDepth = getDepth(root.left);
        int rightDepth = getDepth(root.right);
        return Math.abs(leftDepth - rightDepth) <= 1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);

        
    }
    private int getDepth(TreeNode root){
        if(root == null){
            return 0;
        }
        // 计算高度,这里也需要递归操作
        return Math.max(getDepth(root.left) , getDepth(root.right)) + 1;
    }
}

思路:这里面涉及到两个知识。求二叉树的高度,利用递归。每一层,找左右子树的最大高度,然后加一。

判断是否是平衡二叉树,首先root的高度差是<= 1的,并且它的左右子树也得这样,所有最后return的部分是三个内容进行&&操作。

全部评论

相关推荐

09-13 10:40
门头沟学院 Java
听别人介绍,刷了一堆力扣题,考场上写函数,一直无法通过。赛后才知道要自己写输入输出,力扣害人不浅
Silencer76:输入输出练习题单,请https://www.nowcoder.com/exam/oj?page=1&tab=%E7%AE%97%E6%B3%95%E7%AC%94%E9%9D%A2%E8%AF%95%E7%AF%87&topicId=372
点赞 评论 收藏
分享
头像 会员标识
08-20 18:46
门头沟学院 C++
投递华为技术有限公司等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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