题解 | #平衡二叉树#

平衡二叉树

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

递归标准思路,拆解子问题

public class Solution {
    static boolean res=true;
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null){
            return true;
        }
        fun(root);
        return res;
    }
    //返回当前树深度度
    public int fun(TreeNode root){
        if(root==null){
            return 0;
        }
        int leftlength=fun(root.left);
        int rightlength=fun(root.right);
        //如果当前节点的左右子树深度差超过1,直接把结果标识更新为false
        if(Math.abs(leftlength-rightlength)>1){
            res=false;
        }
        //左右子树深度合法,则返回大深度+1(加上当前头)
        return Math.max(leftlength,rightlength)+1;
    }
}
全部评论

相关推荐

笑着秋招😊:我一直认为努力有回报是一件很幸福很幸福的事情,恭喜你
点赞 评论 收藏
分享
牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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