leetcode 110. balanced binary tree

110. Balanced Binary Tree

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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

1
2
3
4
5
  3
/
9 20
/
15 7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

1
2
3
4
5
6
7
      1
/
2 2
/
3 3
/
4 4

Return false.

Solution

Language: 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
29
30
31
32
33
34
35
36
37
38
39
40

* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class {
class Result {
int depth;
boolean isBalanced;
Result(int depth, boolean isBalanced) {
this.depth = depth;
this.isBalanced = isBalanced;
}
}

public boolean isBalanced(TreeNode root) {
Result r = helper(root);
return r.isBalanced;
}

private Result helper(TreeNode root) {
if (root == null) {
return new Result(0, true);
}
if (root.left == null && root.right == null) {
return new Result(1, true);
}
Result leftResult = helper(root.left);
Result rightResult = helper(root.right);
if (leftResult.isBalanced && rightResult.isBalanced
&& Math.abs(leftResult.depth - rightResult.depth) <= 1) {
return new Result(Math.max(leftResult.depth, rightResult.depth) + 1, true);
}
return new Result(0, false);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class  {
public boolean isBalanced(TreeNode root) {
int r = helper(root);
return r != -1;
}

private int helper(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int left = helper(root.left);
int right = helper(root.right);
if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
}