Skip to content

Commit 1fa8ee6

Browse files
Create Balance binary tree
add balance binary tree in java program
1 parent a163816 commit 1fa8ee6

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.coding.patterns.tree;
2+
3+
class BalancedBinaryTree {
4+
5+
private static Pair<Boolean, Integer> dfs(TreeNode root) {
6+
if (root == null) {
7+
return new Pair<Boolean, Integer>(true, 0);
8+
}
9+
10+
var left = dfs(root.left);
11+
var right = dfs(root.right);
12+
13+
var balanced =
14+
left.getKey() &&
15+
right.getKey() &&
16+
(Math.abs(left.getValue() - right.getValue()) <= 1);
17+
18+
return new Pair<Boolean, Integer>(
19+
balanced,
20+
1 + Math.max(left.getValue(), right.getValue())
21+
);
22+
}
23+
24+
public static boolean isBalanced(TreeNode root) {
25+
return dfs(root).getKey();
26+
}
27+
}
28+
29+
// Solution using the bottom up approach
30+
// TC and SC is On
31+
32+
class Solution {
33+
34+
public int height(TreeNode root){
35+
if(root == null){
36+
return 0;
37+
}
38+
39+
int lh = height(root.left);
40+
int rh = height(root.right);
41+
42+
return 1 + Math.max(lh,rh);
43+
}
44+
45+
public boolean isBalanced(TreeNode root) {
46+
47+
if(root == null){
48+
return true;
49+
}
50+
51+
int lh = height(root.left);
52+
int rh = height(root.right);
53+
54+
return Math.abs(lh - rh) <= 1 && isBalanced(root.left) && isBalanced(root.right);
55+
}
56+
}

0 commit comments

Comments
 (0)