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

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

  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;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务