LeetCode110 判断平衡二叉树

自上而下O(N^2):

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int left = depth(root.left);
        int right = depth(root.right);
        return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }
    public int depth(TreeNode root){
        if(root == null) return 0;
        return Math.max(depth(root.left), depth(root.right)) + 1;
    }
}

自下而上O(N):

 public boolean isBalanced(TreeNode root) {
            if(root == null){
                return true;
            }
            return height(root)!=-1;
        }
        private int height(TreeNode root){
            if(root == null) return 0;
            int lH = height(root.left);
            if(lH == -1) return -1;
            int rH = height(root.right);
            if(rH == -1) return -1;
            if(Math.abs(lH - rH) > 1) return -1;
            return Math.max(lH, rH) + 1;
        }

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/85340906