110. Balanced Binary Tree

Total Accepted: 96062
Total Submissions: 287739
Difficulty: Easy

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        return check(root)!=-1;
    }

    public int check(TreeNode root){
        if(root==null)
            return 0;
        int lh=check(root.left);
        if(lh==-1)
            return -1;
        int rh=check(root.right);
        if(rh==-1)
            return -1;
        if(Math.abs(lh-rh)>1)
            return -1;
        return 1+Math.max(lh, rh);
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。