Skip to content

Commit d422eca

Browse files
authored
Create week 3 110. Balanced Binary Tree
1 parent d3bba87 commit d422eca

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

week 3 110. Balanced Binary Tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
public boolean isBalanced(TreeNode root) {
12+
if (root == null)
13+
return true;
14+
15+
if (getHeight(root) == -1)
16+
return false;
17+
18+
return true;
19+
}
20+
public int getHeight(TreeNode root) {
21+
if (root == null)
22+
return 0;
23+
24+
int left = getHeight(root.left);
25+
int right = getHeight(root.right);
26+
27+
if (left == -1 || right == -1)
28+
return -1;
29+
30+
if (Math.abs(left - right) > 1) {
31+
return -1;
32+
}
33+
34+
return Math.max(left, right) + 1;
35+
36+
}
37+
}

0 commit comments

Comments
 (0)