forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0110-balanced-binary-tree.java
56 lines (41 loc) · 1.23 KB
/
0110-balanced-binary-tree.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.coding.patterns.tree;
class BalancedBinaryTree {
private static Pair<Boolean, Integer> dfs(TreeNode root) {
if (root == null) {
return new Pair<Boolean, Integer>(true, 0);
}
var left = dfs(root.left);
var right = dfs(root.right);
var balanced =
left.getKey() &&
right.getKey() &&
(Math.abs(left.getValue() - right.getValue()) <= 1);
return new Pair<Boolean, Integer>(
balanced,
1 + Math.max(left.getValue(), right.getValue())
);
}
public static boolean isBalanced(TreeNode root) {
return dfs(root).getKey();
}
}
// Solution using the bottom up approach
// TC and SC is On
class Solution {
public int height(TreeNode root){
if(root == null){
return 0;
}
int lh = height(root.left);
int rh = height(root.right);
return 1 + Math.max(lh,rh);
}
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
int lh = height(root.left);
int rh = height(root.right);
return Math.abs(lh - rh) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}