题解 | #平衡二叉树#

平衡二叉树

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;
    }
}
全部评论

相关推荐

每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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