generated from filipe1309/shubcogen-template
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsolution-1.ts
More file actions
28 lines (25 loc) · 869 Bytes
/
solution-1.ts
File metadata and controls
28 lines (25 loc) · 869 Bytes
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
class TreeInfo {
isBalanced: boolean;
height: number;
constructor(isBalanced: boolean, height: number) {
this.isBalanced = isBalanced;
this.height = height;
}
}
// DFS + TreeInfo Obj approach
// Complexity (worst-case): time O(n) | space O(h)
// where n = number of nodes in the tree
// and h = height of the tree
function heightBalancedBinaryTree(tree: BinaryTree) {
return getTreeInfo(tree).isBalanced;
}
function getTreeInfo(node: BinaryTree | null): TreeInfo {
if (!node) return new TreeInfo(true, -1);
const left = getTreeInfo(node.left);
const right = getTreeInfo(node.right);
const isBalance = left.isBalanced && right.isBalanced &&
Math.abs(left.height - right.height) <= 1;
const currHeight = Math.max(left.height, right.height) + 1
return new TreeInfo(isBalance, currHeight);
}
export default heightBalancedBinaryTree;