-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarySearchTree.js
81 lines (71 loc) · 1.91 KB
/
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
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
72
73
74
75
76
77
78
79
80
81
// Binary Search Tree
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
this.count = 0;
}
}
class BinarySearchTree {
constructor(value = "") {
this.root = null;
if (value.toString().trim()) this.root = new Node(value);
}
insert(value) {
const newNode = new Node(value);
if (!this.root) return (this.root = newNode);
let currentNode = this.root;
// O(n)
while (currentNode) {
if (value <= currentNode.value) {
if (currentNode.value === value) return currentNode.count++;
if (!currentNode.left) return (currentNode.left = newNode);
currentNode = currentNode.left;
} else {
if (currentNode.value === value) return currentNode.count++;
if (!currentNode.right) return (currentNode.right = newNode);
currentNode = currentNode.right;
}
}
}
insertArray(array) {
// O(n)
array.forEach((value) => this.insert(value));
}
findMin() {
let currentNode = this.root;
// O(n)
while (currentNode) {
if (currentNode.left === null) return currentNode.value;
currentNode = currentNode.left;
}
}
findMax() {
let currentNode = this.root;
// O(n)
while (currentNode) {
if (currentNode.right === null) return currentNode.value;
currentNode = currentNode.right;
}
}
contains(value) {
let currentNode = this.root;
// O(n)
while (currentNode) {
if (value <= currentNode.value) {
if (value === currentNode.value) return true;
currentNode = currentNode.left;
} else {
if (value === currentNode.value) return true;
currentNode = currentNode.right;
}
}
return false;
}
}
const binarysearchTree = new BinarySearchTree(10);
binarysearchTree.insert(5);
binarysearchTree.insertArray([3, 55, 2, 3]);
binarysearchTree.contains(1);
console.log(binarysearchTree);