-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path110.spec.ts
71 lines (55 loc) · 1.61 KB
/
110.spec.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
*/
class BinaryTree {
root: TreeNode | null;
constructor() {
this.root = null;
}
insertNode(node: TreeNode, newNode: TreeNode): void {
if (newNode.value < node.value) {
if (!this.root)
node.left = newNode;
else
this.insertNode(node.left, newNode);
}
else {
if (!this.root)
node.right = newNode;
else
this.insertNode(node.right, newNode);
}
}
insert(value: number): void {
const newNode = new TreeNode(value);
if (!this.root)
this.root = newNode;
else
this.insertNode(this.root, newNode);
}
searchNode(node: TreeNode | null, value: number): boolean {
if (!this.root)
return false;
if (value < node.value)
return this.searchNode(node.left, value);
else if (value > node.value)
return this.searchNode(node.right, value);
else
return true;
}
search(value: number): boolean {
return this.searchNode(this.root, value);
}
}
/** @param Treenode - node */
function isBalanced(root: TreeNode | null): boolean {
if (!root)
return true;
return isBalanced(root.left) && isBalanced(root.right) && Math.abs(getHeigth(root.left) - getHeigth(root.right)) <= 1;
};
const getHeigth = (node: TreeNode): number => {
if (!node)
return 0;
return Math.max(getHeigth(node.left), getHeigth(node.right)) + 1;
}