-
Notifications
You must be signed in to change notification settings - Fork 929
/
binary-search-tree.js
308 lines (273 loc) · 9.12 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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
const BinaryTreeNode = require('./binary-tree-node');
const Queue = require('../queues/queue');
const Stack = require('../stacks/stack');
// tag::snippet[]
class BinarySearchTree {
constructor() {
this.root = null;
this.size = 0;
}
// end::snippet[]
// tag::add[]
/**
* Insert value on the BST.
*
* If the value is already in the tree,
* then it increases the multiplicity value
* @param {any} value node's value to insert in the tree
* @returns {BinaryTreeNode} newly added node
*/
add(value) {
let node = new BinaryTreeNode(value);
if (this.root) {
const { found, parent } = this.findNodeAndParent(value); // <1>
if (found) { // duplicated: value already exist on the tree
found.meta.multiplicity = (found.meta.multiplicity || 1) + 1; // <2>
node = found;
} else if (value < parent.value) {
parent.setLeftAndUpdateParent(node);
} else {
parent.setRightAndUpdateParent(node);
}
} else {
this.root = node;
}
this.size += 1;
return node;
}
// end::add[]
/**
* Find if a node is present or not
* @param {any} value node to find
* @returns {boolean} true if is present, false otherwise
*/
has(value) {
return !!this.find(value);
}
// tag::find[]
/**
* @param {any} value value to find
* @returns {BinaryTreeNode|null} node if it found it or null if not
*/
find(value) {
return this.findNodeAndParent(value).found;
}
/**
* Recursively finds the node matching the value.
* If it doesn't find, it returns the leaf `parent` where the new value should be appended.
* @param {any} value Node's value to find
* @param {BinaryTreeNode} node first element to start the search (root is default)
* @param {BinaryTreeNode} parent keep track of parent (usually filled by recursion)
* @returns {object} node and its parent like {node, parent}
*/
findNodeAndParent(value, node = this.root, parent = null) {
if (!node || node.value === value) {
return { found: node, parent };
} if (value < node.value) {
return this.findNodeAndParent(value, node.left, node);
}
return this.findNodeAndParent(value, node.right, node);
}
// end::find[]
/**
* Get the node with the max value of subtree: the right-most value.
* @param {BinaryTreeNode} node subtree's root
* @returns {BinaryTreeNode} right-most node (max value)
*/
getRightmost(node = this.root) {
if (!node || !node.right) {
return node;
}
return this.getMax(node.right);
}
// tag::leftMost[]
/**
* Get the node with the min value of subtree: the left-most value.
* @param {BinaryTreeNode} node subtree's root
* @returns {BinaryTreeNode} left-most node (min value)
*/
getLeftmost(node = this.root) {
if (!node || !node.left) {
return node;
}
return this.getMin(node.left);
}
// end::leftMost[]
// tag::remove[]
/**
* Remove a node from the tree
* @returns {boolean} false if not found and true if it was deleted
*/
remove(value) {
const { found: nodeToRemove, parent } = this.findNodeAndParent(value); // <1>
if (!nodeToRemove) return false; // <2>
// Combine left and right children into one subtree without nodeToRemove
const removedNodeChildren = this.combineLeftIntoRightSubtree(nodeToRemove); // <3>
if (nodeToRemove.meta.multiplicity && nodeToRemove.meta.multiplicity > 1) { // <4>
nodeToRemove.meta.multiplicity -= 1; // handles duplicated
} else if (nodeToRemove === this.root) { // <5>
// Replace (root) node to delete with the combined subtree.
this.root = removedNodeChildren;
if (this.root) { this.root.parent = null; } // clearing up old parent
} else if (nodeToRemove.isParentLeftChild) { // <6>
// Replace node to delete with the combined subtree.
parent.setLeftAndUpdateParent(removedNodeChildren);
} else {
parent.setRightAndUpdateParent(removedNodeChildren);
}
this.size -= 1;
return true;
}
// end::remove[]
// tag::combine[]
/**
* Combine left into right children into one subtree without given parent node.
*
* @example combineLeftIntoRightSubtree(30)
*
* 30* 40
* / \ / \
* 10 40 combined 35 50
* \ / \ ----------> /
* 15 35 50 10
* \
* 15
*
* It takes node 30 left subtree (10 and 15) and put it in the
* leftmost node of the right subtree (40, 35, 50).
*
* @param {BinaryTreeNode} node
* @returns {BinaryTreeNode} combined subtree
*/
combineLeftIntoRightSubtree(node) {
if (node.right) {
const leftmost = this.getLeftmost(node.right);
leftmost.setLeftAndUpdateParent(node.left);
return node.right;
}
return node.left;
}
// end::combine[]
// tag::bfs[]
/**
* Breath-first search for a tree (always starting from the root element).
* @yields {BinaryTreeNode}
*/
* bfs() {
const queue = new Queue();
queue.add(this.root);
while (!queue.isEmpty()) {
const node = queue.remove();
yield node;
if (node.left) { queue.add(node.left); }
if (node.right) { queue.add(node.right); }
}
}
// end::bfs[]
// tag::dfs[]
/**
* Depth-first search for a tree (always starting from the root element)
* @see preOrderTraversal Similar results to the pre-order transversal.
* @yields {BinaryTreeNode}
*/
* dfs() {
const stack = new Stack();
stack.add(this.root);
while (!stack.isEmpty()) {
const node = stack.remove();
yield node;
if (node.right) { stack.add(node.right); }
if (node.left) { stack.add(node.left); }
}
}
// end::dfs[]
// tag::inOrderTraversal[]
/**
* In-order traversal on a tree: left-root-right.
* If the tree is a BST, then the values will be sorted in ascendent order
* @param {BinaryTreeNode} node first node to start the traversal
* @yields {BinaryTreeNode}
*/
* inOrderTraversal(node = this.root) {
if (node && node.left) { yield* this.inOrderTraversal(node.left); }
yield node;
if (node && node.right) { yield* this.inOrderTraversal(node.right); }
}
// end::inOrderTraversal[]
// tag::preOrderTraversal[]
/**
* Pre-order traversal on a tree: root-left-right.
* Similar results to DFS
* @param {BinaryTreeNode} node first node to start the traversal
* @yields {BinaryTreeNode}
*/
* preOrderTraversal(node = this.root) {
yield node;
if (node.left) { yield* this.preOrderTraversal(node.left); }
if (node.right) { yield* this.preOrderTraversal(node.right); }
}
// end::preOrderTraversal[]
// tag::postOrderTraversal[]
/**
* Post-order traversal on a tree: left-right-root.
* @param {BinaryTreeNode} node first node to start the traversal
* @yields {BinaryTreeNode}
*/
* postOrderTraversal(node = this.root) {
if (node.left) { yield* this.postOrderTraversal(node.left); }
if (node.right) { yield* this.postOrderTraversal(node.right); }
yield node;
}
// end::postOrderTraversal[]
/**
* Represent Binary Tree as an array.
*
* Leaf nodes will have two `undefined` descendants.
*
* The array representation of the binary tree is as follows:
*
* First element (index=0) is the root.
* The following two elements (index=1,2) are descendants of the root: left (a) and right (b).
* The next two elements (index=3,4) are the descendants of a
* The next two elements (index=5,6) are the descendants of b and so on.
*
* 0 1 2 3 4 5 6 n
* [root, a=root.left, b=root.right, a.left, a.right, b.left, b.right, ...]
*
* You can also find the parents as follows
*
* e.g.
* Parent 0: children 1,2
* Parent 1: children 3,4
* Parent 2: children 5,6
* Parent 3: children 7,8
*
* Given any index you can find the parent index with the following formula:
*
* parent = (index) => Math.floor((index-1)/2)
*/
toArray() {
const array = [];
const queue = new Queue();
const visited = new Map();
if (this.root) { queue.add(this.root); }
while (!queue.isEmpty()) {
const current = queue.remove();
array.push(current && current.value);
if (current) { visited.set(current); }
if (current && !visited.has(current.left)) { queue.add(current.left); }
if (current && !visited.has(current.right)) { queue.add(current.right); }
}
return array;
}
}
// aliases
BinarySearchTree.prototype.insert = BinarySearchTree.prototype.add;
BinarySearchTree.prototype.set = BinarySearchTree.prototype.add;
BinarySearchTree.prototype.delete = BinarySearchTree.prototype.remove;
BinarySearchTree.prototype.getMin = BinarySearchTree.prototype.getLeftmost;
BinarySearchTree.prototype.minimum = BinarySearchTree.prototype.getMin;
BinarySearchTree.prototype.getMax = BinarySearchTree.prototype.getRightmost;
BinarySearchTree.prototype.maximum = BinarySearchTree.prototype.getMax;
BinarySearchTree.prototype.get = BinarySearchTree.prototype.find;
module.exports = BinarySearchTree;