-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-search-tree.js
60 lines (50 loc) · 1.23 KB
/
binary-search-tree.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
// inserting a node:
insert(value) {
const newNode = new Node(value);
if (this.root === null) {
this.root = newNode;
return this;
}
let currentNode = this.root;
while (currentNode !== null) {
if (value === currentNode.value) return undefined;
if (value < currentNode.value) {
if (currentNode.left === null) {
currentNode.left = newNode;
return this;
}
currentNode = currentNode.left;
} else {
if (currentNode.right === null) {
currentNode.right = newNode;
return this;
}
currentNode = currentNode.right;
}
}
}
// searching a node:
search(value) {
if (!this.root) return false;
let currentNode = this.root;
let found = false;
while (currentNode !== null && !found) {
if (value < currentNode) currentNode = currentNode.left;
else if (value > currentNode) currentNode = currentNode.right;
else found = currentNode;
}
if (!found) return undefined;
return found;
}
}