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

稍微做的有点久,学到了两点:

  1. 用负数(或为用到的int范围)来代表布尔值
  2. 剪枝操作。如该题的搜索其实还是遵循的后续遍历,所以实际上时间复杂度是O(N)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return bool布尔型
     */
    public int IsBalanced(TreeNode pRoot) {
        if(pRoot == null)
            return 0;
        int left = IsBalanced(pRoot.left);
        if(left == -1)
            return -1;
        int right = IsBalanced(pRoot.right);
        if(right == -1)
            return -1;
        if(Math.abs(left-right)>1)
            return -1;
        return Math.max(left, right) +1 ;
    }
    public int depth (TreeNode pRoot) {
        if(pRoot == null)
            return 0;
        return Math.max(depth(pRoot.left), depth(pRoot.right))+1;
    }


    public boolean IsBalanced_Solution (TreeNode pRoot) {
        // write code here
        if(pRoot == null)
            return true;
        if( IsBalanced(pRoot) != -1)
            return true;
        return false;
    }
}

全部评论

相关推荐

01-12 17:45
门头沟学院 Java
叁六玖:这样的应该钱不多,以前我也被问,我在问他们实习公工资多少,一般都是2200-2800
找实习记录
点赞 评论 收藏
分享
2025-12-17 12:08
门头沟学院 产品经理
牛客85811352...:1希音不知道算不算大厂 2完全符合,过得很舒服, 3确实只有杂活 领导找我续签到明年3、4月我要继续吗。主要是边实习边秋招这段时间还是有点累
什么是优秀的实习经历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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