题解 | #判断平衡二叉树#从小白到30题,100道还很远吗

判断是不是平衡二叉树

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

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return bool布尔型
     */
    public boolean IsBalanced_Solution (TreeNode pRoot) {
        // write code here
        if(pRoot==null) return true;
        int left_height=tree_high(pRoot.left);
        int right_height=tree_high(pRoot.right);
        if((left_height-right_height>1)||(left_height-right_height<-1))//高度差超过1不行
        return false;
        if(IsBalanced_Solution(pRoot.left)&&IsBalanced_Solution(pRoot.right))//左右有一个不平衡不行
            return true;
        else return false;

    }
    public int tree_high(TreeNode pRoot){//计算树的高度
        if(pRoot==null) return 0;
        int left=1+tree_high(pRoot.left);
        int right=1+tree_high(pRoot.right);
        return Math.max(left,right);
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 17:58
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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