-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-search-tree.ts
69 lines (60 loc) · 1.43 KB
/
binary-search-tree.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
interface Node {
value: number;
left: Node;
right: Node;
}
export default class BinarySearchTree {
private root: Node;
constructor() {
this.root = null;
}
contains(value: number): boolean {
let current = this.root;
while (current) {
if (value > current.value) {
current = current.right;
} else if (value < current.value) {
current = current.left;
} else {
return true;
}
}
return false;
}
add(value: number): void {
const node = {
value,
left: null,
right: null,
}
let current = this.root;
if (this.root === null) {
this.root = node;
return;
}
// Loop until value is added or we discover that it already exists in tree
while (true) {
// Move right if value is greater
if (value > current.value) {
// If right node doesn't exist, set it to our node and stop traversing
if (!current.right) {
current.right = node;
break;
}
// Else move to right node
current = current.right;
// Move left if value is smaller
} else if (value < current.value) {
// If left node doesn't exist, set it to our node and stop traversing
if (!current.left) {
current.left = node;
break;
}
// Else move to left node
current = current.left;
} else {
break;
}
}
}
}