forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinarySearchTree.js
39 lines (32 loc) · 1021 Bytes
/
BinarySearchTree.js
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
import BinarySearchTreeNode from './BinarySearchTreeNode';
export default class BinarySearchTree {
constructor() {
this.root = new BinarySearchTreeNode();
}
insert(value) {
this.root.insert(value);
}
contains(value) {
return this.root.contains(value);
}
remove(value) {
const nodeToRemove = this.findNode(value);
if (!nodeToRemove) {
throw new Error('Item not found in the tree');
}
if (!nodeToRemove.left && !nodeToRemove.right) {
// Node is a leaf and thus has no children.
// Just remove the pointer to this node from the parent node.
} else if (nodeToRemove.left && nodeToRemove.right) {
// Node has two children.
// Find the next biggest value (minimum value in the right branch)
// and replace current value node with that next biggest value.
} else {
// Node has only one child.
// Make this child to be a direct child of current node's parent.
}
}
toString() {
return this.root.toString();
}
}