Skip to content

Commit 0464cba

Browse files
authored
Create 110. Balanced Binary Tree
1 parent f5cd4ad commit 0464cba

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

110. Balanced Binary Tree

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/****
2+
Given a binary tree, determine if it is height-balanced.
3+
For this problem, a height-balanced binary tree is defined as a binary tree,
4+
in which the depth of the two subtrees of every node never differ by more than 1.
5+
****/
6+
7+
//Java solution:
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* int val;
13+
* TreeNode left;
14+
* TreeNode right;
15+
* TreeNode(int x) { val = x; }
16+
* }
17+
*/
18+
public class Solution {
19+
public int depth(TreeNode node){
20+
if(node == null){
21+
return 0;
22+
}
23+
else if(node.left == null && node.right == null){
24+
return 1;
25+
}
26+
else{
27+
int left = depth(node.left);
28+
int right = depth(node.right);
29+
return Math.max(left, right) + 1;
30+
}
31+
}
32+
33+
public boolean isBalanced(TreeNode root) {
34+
if(root == null){
35+
return true;
36+
}
37+
int left = depth(root.left);
38+
int right = depth(root.right);
39+
40+
if(Math.abs(left - right) > 1){
41+
return false;
42+
}
43+
return isBalanced(root.left) && isBalanced(root.right);
44+
}
45+
}

0 commit comments

Comments
 (0)