/
binarysearchtree.js
136 lines (108 loc) · 2.85 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
const createNode = (value) => {
return {
value,
left: null,
right: null
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
if (this.isEmpty()) {
this.root = createNode(value);
return this.root.value;
}
let current = this.root;
while (current) {
if (value < current.value) {
if (!current.left) {
current.left = createNode(value);
return value;
}
current = current.left;
} else {
if (!current.right) {
current.right = createNode(value);
return value;
}
current = current.right;
}
}
}
lookup(value) {
let current = this.root;
while (current) {
if (value < current.value) {
current = current.left;
} else if (value > current.value) {
current = current.right;
} else {
return current;
}
}
return null;
}
remove(value) {
if (!this.root) return false;
let current = this.root;
let prev = null;
let successor = null;
let prevSuccessor = null;
while (current && current.value !== value) {
prev = current;
if (value < current.value) {
current = current.left;
} else if (value > current.value) {
current = current.right;
}
}
if (!current) return false;
if (!current.right) {
successor = current.left;
} else {
successor = current.right;
while (successor.left) {
prevSuccessor = successor;
successor = successor.left;
}
}
if (prev.left === current) prev.left = successor;
else prev.right = successor;
if (!current.right) {
return this;
} else if (!current.right.left) {
successor.left = current.left;
return this;
} else {
prevSuccessor.left = successor.right;
successor.left = current.left;
successor.right = current.right;
}
return this;
}
isEmpty() {
return this.root === null;
}
}
const bst = new BinarySearchTree();
// bst.insert(9);
// bst.insert(4);
// bst.insert(20);
// bst.insert(1);
// bst.insert(6);
// bst.insert(15);
// bst.insert(170);
// console.log(bst.root);
// console.log(bst.lookup(15));
bst.insert(46);
bst.insert(8);
bst.insert(6);
bst.insert(20);
bst.insert(15);
bst.insert(10);
bst.insert(12);
console.log(bst.root);
bst.remove(8);
console.log(bst.root);