-
Notifications
You must be signed in to change notification settings - Fork 9
/
bst.ts
543 lines (506 loc) · 21.6 KB
/
bst.ts
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/**
* data-structure-typed
*
* @author Tyler Zeng
* @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
* @license MIT License
*/
import type {
BinaryTreeNodeId,
BinaryTreeNodePropertyName,
BSTComparator,
BSTNodeNested,
BSTOptions
} from '../../types';
import { CP, LoopType } from '../../types';
import { BinaryTree, BinaryTreeNode } from './binary-tree';
import { IBST, IBSTNode } from '../../interfaces';
export class BSTNode<T = any, NEIGHBOR extends BSTNode<T, NEIGHBOR> = BSTNodeNested<T>>
extends BinaryTreeNode<T, NEIGHBOR>
implements IBSTNode<T, NEIGHBOR>
{
constructor(id: BinaryTreeNodeId, val?: T) {
super(id, val);
}
}
export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N> implements IBST<N> {
/**
* The constructor function initializes a binary search tree object with an optional comparator function.
* @param {BSTOptions} [options] - An optional object that contains configuration options for the binary search tree.
*/
constructor(options?: BSTOptions) {
super(options);
if (options !== undefined) {
const { comparator } = options;
if (comparator !== undefined) {
this._comparator = comparator;
}
}
}
/**
* The function creates a new binary search tree node with the given id and value.
* @param {BinaryTreeNodeId} id - The `id` parameter is the identifier for the binary tree node. It is used to uniquely
* identify each node in the binary tree.
* @param [val] - The `val` parameter is an optional value that can be assigned to the node. It represents the value
* that will be stored in the node.
* @returns a new instance of the BSTNode class with the specified id and value.
*/
override createNode(id: BinaryTreeNodeId, val?: N['val']): N {
return new BSTNode<N['val'], N>(id, val) as N;
}
/**
* The `add` function adds a new node to a binary search tree, either by creating a new node or by updating an existing
* node with the same ID.
* @param {BinaryTreeNodeId | N | null} idOrNode - The `idOrNode` parameter can be either a `BinaryTreeNodeId` or a `N`
* (which represents a binary tree node) or `null`.
* @param [val] - The `val` parameter is an optional value that can be assigned to the `val` property of the new node
* being added to the binary search tree.
* @returns The function `add` returns the inserted node (`inserted`) which can be of type `N`, `null`, or `undefined`.
*/
override add(idOrNode: BinaryTreeNodeId | N | null, val?: N['val']): N | null | undefined {
// TODO support node as a param
let inserted: N | null = null;
let newNode: N | null = null;
if (idOrNode instanceof BSTNode) {
newNode = idOrNode;
} else if (typeof idOrNode === 'number') {
newNode = this.createNode(idOrNode, val);
} else if (idOrNode === null) {
newNode = null;
}
if (this.root === null) {
this._setRoot(newNode);
this._setSize(this.size + 1);
inserted = this.root;
} else {
let cur = this.root;
let traversing = true;
while (traversing) {
if (cur !== null && newNode !== null) {
if (this._compare(cur.id, newNode.id) === CP.eq) {
if (newNode) {
cur.val = newNode.val;
}
//Duplicates are not accepted.
traversing = false;
inserted = cur;
} else if (this._compare(cur.id, newNode.id) === CP.gt) {
// Traverse left of the node
if (cur.left === undefined) {
if (newNode) {
newNode.parent = cur;
}
//Add to the left of the current node
cur.left = newNode;
this._setSize(this.size + 1);
traversing = false;
inserted = cur.left;
} else {
//Traverse the left of the current node
if (cur.left) cur = cur.left;
}
} else if (this._compare(cur.id, newNode.id) === CP.lt) {
// Traverse right of the node
if (cur.right === undefined) {
if (newNode) {
newNode.parent = cur;
}
//Add to the right of the current node
cur.right = newNode;
this._setSize(this.size + 1);
traversing = false;
inserted = cur.right;
} else {
//Traverse the left of the current node
if (cur.right) cur = cur.right;
}
}
} else {
traversing = false;
}
}
}
return inserted;
}
/**
* The `addMany` function overrides the base class method to add multiple nodes to a binary search tree in a balanced
* manner.
* @param {[BinaryTreeNodeId | N , N['val']][]} idsOrNodes - The `idsOrNodes` parameter in the `addMany` function is an array of
* `BinaryTreeNodeId` or `N` (node) objects, or `null` values. It represents the nodes or node IDs that need to be added
* to the binary search tree.
* @param {N['val'][]} data - The values of tree nodes
* @param {boolean} isBalanceAdd - If true the nodes will be balance inserted in binary search method.
* @returns The function `addMany` returns an array of `N`, `null`, or `undefined` values.
*/
override addMany(
idsOrNodes: (BinaryTreeNodeId | null)[] | (N | null)[],
data?: N['val'][],
isBalanceAdd = false
): (N | null | undefined)[] {
function hasNoNull(arr: (BinaryTreeNodeId | null)[] | (N | null)[]): arr is BinaryTreeNodeId[] | N[] {
return arr.indexOf(null) === -1;
}
if (!isBalanceAdd || !hasNoNull(idsOrNodes)) {
return super.addMany(idsOrNodes, data);
}
const inserted: (N | null | undefined)[] = [];
const combinedArr: [BinaryTreeNodeId | N, N['val']][] = idsOrNodes.map((value, index) => [value, data?.[index]]);
let sorted = [];
function isNodeOrNullTuple(arr: [BinaryTreeNodeId | N, N['val']][]): arr is [N, N['val']][] {
for (const [idOrNode] of arr) if (idOrNode instanceof BSTNode) return true;
return false;
}
function isBinaryTreeIdOrNullTuple(arr: [BinaryTreeNodeId | N, N['val']][]): arr is [BinaryTreeNodeId, N['val']][] {
for (const [idOrNode] of arr) if (typeof idOrNode === 'number') return true;
return false;
}
let sortedIdsOrNodes: (number | N | null)[] = [],
sortedData: (N['val'] | undefined)[] | undefined = [];
if (isNodeOrNullTuple(combinedArr)) {
sorted = combinedArr.sort((a, b) => a[0].id - b[0].id);
} else if (isBinaryTreeIdOrNullTuple(combinedArr)) {
sorted = combinedArr.sort((a, b) => a[0] - b[0]);
} else {
throw new Error('Invalid input idsOrNodes');
}
sortedIdsOrNodes = sorted.map(([idOrNode]) => idOrNode);
sortedData = sorted.map(([, val]) => val);
const recursive = (arr: (BinaryTreeNodeId | null | N)[], data?: N['val'][]) => {
if (arr.length === 0) return;
const mid = Math.floor((arr.length - 1) / 2);
const newNode = this.add(arr[mid], data?.[mid]);
inserted.push(newNode);
recursive(arr.slice(0, mid), data?.slice(0, mid));
recursive(arr.slice(mid + 1), data?.slice(mid + 1));
};
const iterative = () => {
const n = sorted.length;
const stack: [[number, number]] = [[0, n - 1]];
while (stack.length > 0) {
const popped = stack.pop();
if (popped) {
const [l, r] = popped;
if (l <= r) {
const m = l + Math.floor((r - l) / 2);
const newNode = this.add(sortedIdsOrNodes[m], sortedData?.[m]);
inserted.push(newNode);
stack.push([m + 1, r]);
stack.push([l, m - 1]);
}
}
}
};
if (this.loopType === LoopType.RECURSIVE) {
recursive(sortedIdsOrNodes, sortedData);
} else {
iterative();
}
return inserted;
}
/**
* The function returns the first node in a binary tree that matches the given property name and value.
* @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
* generic type `N`. It represents the property of the binary tree node that you want to search for.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* specifies the property name to use for searching the binary tree nodes. If not provided, it defaults to `'id'`.
* @returns The method is returning either a BinaryTreeNodeId or N (generic type) or null.
*/
override get(nodeProperty: BinaryTreeNodeId | N, propertyName?: BinaryTreeNodePropertyName): N | null {
propertyName = propertyName ?? 'id';
return this.getNodes(nodeProperty, propertyName, true)[0] ?? null;
}
/**
* The function returns the id of the rightmost node if the comparison between two values is less than, the id of the
* leftmost node if the comparison is greater than, and the id of the rightmost node otherwise.
* @returns The method `lastKey()` returns the id of the rightmost node in the binary tree if the comparison between
* the values at index 0 and 1 is less than, otherwise it returns the id of the leftmost node. If the comparison is
* equal, it returns the id of the rightmost node. If there are no nodes in the tree, it returns 0.
*/
lastKey(): BinaryTreeNodeId {
if (this._compare(0, 1) === CP.lt) return this.getRightMost()?.id ?? 0;
else if (this._compare(0, 1) === CP.gt) return this.getLeftMost()?.id ?? 0;
else return this.getRightMost()?.id ?? 0;
}
/**
* The function `getNodes` returns an array of nodes in a binary tree that match a given property value.
* @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or an
* `N` type. It represents the property of the binary tree node that you want to compare with.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* specifies the property name to use for comparison. If not provided, it defaults to `'id'`.
* @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
* return only one node that matches the given `nodeProperty` or all nodes that match the `nodeProperty`. If `onlyOne`
* is set to `true`, the function will return an array with only one node (if
* @returns an array of nodes (type N).
*/
override getNodes(
nodeProperty: BinaryTreeNodeId | N,
propertyName: BinaryTreeNodePropertyName = 'id',
onlyOne?: boolean
): N[] {
if (!this.root) return [];
const result: N[] = [];
if (this.loopType === LoopType.RECURSIVE) {
const _traverse = (cur: N) => {
if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return;
if (!cur.left && !cur.right) return;
if (propertyName === 'id') {
if (this._compare(cur.id, nodeProperty as number) === CP.gt) cur.left && _traverse(cur.left);
if (this._compare(cur.id, nodeProperty as number) === CP.lt) cur.right && _traverse(cur.right);
} else {
cur.left && _traverse(cur.left);
cur.right && _traverse(cur.right);
}
};
_traverse(this.root);
} else {
const queue: N[] = [this.root];
while (queue.length > 0) {
const cur = queue.shift();
if (cur) {
if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return result;
if (propertyName === 'id') {
if (this._compare(cur.id, nodeProperty as number) === CP.gt) cur.left && queue.push(cur.left);
if (this._compare(cur.id, nodeProperty as number) === CP.lt) cur.right && queue.push(cur.right);
} else {
cur.left && queue.push(cur.left);
cur.right && queue.push(cur.right);
}
}
}
}
return result;
}
// --- start additional functions
/**
* The `lesserSum` function calculates the sum of property values in a binary tree for nodes that have a property value
* less than a given node.
* @param {N | BinaryTreeNodeId | null} beginNode - The `beginNode` parameter can be one of the following:
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* specifies the property name to use for calculating the sum. If not provided, it defaults to `'id'`.
* @returns The function `lesserSum` returns a number, which represents the sum of the values of the nodes in the
* binary tree that have a lesser value than the specified `beginNode` based on the `propertyName`.
*/
lesserSum(beginNode: N | BinaryTreeNodeId | null, propertyName?: BinaryTreeNodePropertyName): number {
propertyName = propertyName ?? 'id';
if (typeof beginNode === 'number') beginNode = this.get(beginNode, 'id');
if (!beginNode) return 0;
if (!this.root) return 0;
const id = beginNode.id;
const getSumByPropertyName = (cur: N) => {
let needSum: number;
switch (propertyName) {
case 'id':
needSum = cur.id;
break;
default:
needSum = cur.id;
break;
}
return needSum;
};
let sum = 0;
if (this.loopType === LoopType.RECURSIVE) {
const _traverse = (cur: N): void => {
const compared = this._compare(cur.id, id);
if (compared === CP.eq) {
if (cur.right) sum += this.subTreeSum(cur.right, propertyName);
return;
} else if (compared === CP.lt) {
if (cur.left) sum += this.subTreeSum(cur.left, propertyName);
sum += getSumByPropertyName(cur);
if (cur.right) _traverse(cur.right);
else return;
} else {
if (cur.left) _traverse(cur.left);
else return;
}
};
_traverse(this.root);
} else {
const queue: N[] = [this.root];
while (queue.length > 0) {
const cur = queue.shift();
if (cur) {
const compared = this._compare(cur.id, id);
if (compared === CP.eq) {
if (cur.right) sum += this.subTreeSum(cur.right, propertyName);
return sum;
} else if (compared === CP.lt) {
// todo maybe a bug
if (cur.left) sum += this.subTreeSum(cur.left, propertyName);
sum += getSumByPropertyName(cur);
if (cur.right) queue.push(cur.right);
else return sum;
} else {
if (cur.left) queue.push(cur.left);
else return sum;
}
}
}
}
return sum;
}
/**
* The `allGreaterNodesAdd` function adds a delta value to the specified property of all nodes in a binary tree that
* have a greater value than a given node.
* @param {N | BinaryTreeNodeId | null} node - The `node` parameter can be either of type `N` (a generic type),
* `BinaryTreeNodeId`, or `null`. It represents the node in the binary tree to which the delta value will be added.
* @param {number} delta - The `delta` parameter is a number that represents the amount by which the property value of
* each greater node should be increased.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* specifies the property name of the nodes in the binary tree that you want to update. If not provided, it defaults to
* 'id'.
* @returns a boolean value.
*/
allGreaterNodesAdd(
node: N | BinaryTreeNodeId | null,
delta: number,
propertyName?: BinaryTreeNodePropertyName
): boolean {
propertyName = propertyName ?? 'id';
if (typeof node === 'number') node = this.get(node, 'id');
if (!node) return false;
const id = node.id;
if (!this.root) return false;
const _sumByPropertyName = (cur: N) => {
switch (propertyName) {
case 'id':
cur.id += delta;
break;
default:
cur.id += delta;
break;
}
};
if (this.loopType === LoopType.RECURSIVE) {
const _traverse = (cur: N) => {
const compared = this._compare(cur.id, id);
if (compared === CP.gt) _sumByPropertyName(cur);
if (!cur.left && !cur.right) return;
if (cur.left && this._compare(cur.left.id, id) === CP.gt) _traverse(cur.left);
if (cur.right && this._compare(cur.right.id, id) === CP.gt) _traverse(cur.right);
};
_traverse(this.root);
return true;
} else {
const queue: N[] = [this.root];
while (queue.length > 0) {
const cur = queue.shift();
if (cur) {
const compared = this._compare(cur.id, id);
if (compared === CP.gt) _sumByPropertyName(cur);
if (cur.left && this._compare(cur.left.id, id) === CP.gt) queue.push(cur.left);
if (cur.right && this._compare(cur.right.id, id) === CP.gt) queue.push(cur.right);
}
}
return true;
}
}
/**
* Balancing Adjustment:
* Perfectly Balanced Binary Tree: Since the balance of a perfectly balanced binary tree is already fixed, no additional balancing adjustment is needed. Any insertion or deletion operation will disrupt the perfect balance, often requiring a complete reconstruction of the tree.
* AVL Tree: After insertion or deletion operations, an AVL tree performs rotation adjustments based on the balance factor of nodes to restore the tree's balance. These rotations can be left rotations, right rotations, left-right rotations, or right-left rotations, performed as needed.
*
* Use Cases and Efficiency:
* Perfectly Balanced Binary Tree: Perfectly balanced binary trees are typically used in specific scenarios such as complete binary heaps in heap sort or certain types of Huffman trees. However, they are not suitable for dynamic operations requiring frequent insertions and deletions, as these operations often necessitate full tree reconstruction.
* AVL Tree: AVL trees are well-suited for scenarios involving frequent searching, insertion, and deletion operations. Through rotation adjustments, AVL trees maintain their balance, ensuring average and worst-case time complexity of O(log n).
*/
/**
* The `perfectlyBalance` function takes a binary tree, performs a depth-first search to sort the nodes, and then
* constructs a balanced binary search tree using either a recursive or iterative approach.
* @returns The function `perfectlyBalance()` returns a boolean value.
*/
perfectlyBalance(): boolean {
const sorted = this.DFS('in', 'node'),
n = sorted.length;
this.clear();
if (sorted.length < 1) return false;
if (this.loopType === LoopType.RECURSIVE) {
const buildBalanceBST = (l: number, r: number) => {
if (l > r) return;
const m = l + Math.floor((r - l) / 2);
const midNode = sorted[m];
this.add(midNode.id, midNode.val);
buildBalanceBST(l, m - 1);
buildBalanceBST(m + 1, r);
};
buildBalanceBST(0, n - 1);
return true;
} else {
const stack: [[number, number]] = [[0, n - 1]];
while (stack.length > 0) {
const popped = stack.pop();
if (popped) {
const [l, r] = popped;
if (l <= r) {
const m = l + Math.floor((r - l) / 2);
const midNode = sorted[m];
this.add(midNode.id, midNode.val);
stack.push([m + 1, r]);
stack.push([l, m - 1]);
}
}
}
return true;
}
}
/**
* The function `isAVLBalanced` checks if a binary tree is balanced according to the AVL tree property.
* @returns a boolean value.
*/
isAVLBalanced(): boolean {
if (!this.root) return true;
let balanced = true;
if (this.loopType === LoopType.RECURSIVE) {
const _height = (cur: N | null | undefined): number => {
if (!cur) return 0;
const leftHeight = _height(cur.left),
rightHeight = _height(cur.right);
if (Math.abs(leftHeight - rightHeight) > 1) balanced = false;
return Math.max(leftHeight, rightHeight) + 1;
};
_height(this.root);
} else {
const stack: N[] = [];
let node: N | null | undefined = this.root,
last: N | null = null;
const depths: Map<N, number> = new Map();
while (stack.length > 0 || node) {
if (node) {
stack.push(node);
node = node.left;
} else {
node = stack[stack.length - 1];
if (!node.right || last === node.right) {
node = stack.pop();
if (node) {
const left = node.left ? depths.get(node.left) ?? -1 : -1;
const right = node.right ? depths.get(node.right) ?? -1 : -1;
if (Math.abs(left - right) > 1) return false;
depths.set(node, 1 + Math.max(left, right));
last = node;
node = null;
}
} else node = node.right;
}
}
}
return balanced;
}
protected _comparator: BSTComparator = (a, b) => a - b;
/**
* The function compares two binary tree node IDs using a comparator function and returns whether the first ID is
* greater than, less than, or equal to the second ID.
* @param {BinaryTreeNodeId} a - a is a BinaryTreeNodeId, which represents the identifier of a binary tree node.
* @param {BinaryTreeNodeId} b - The parameter "b" in the above code refers to a BinaryTreeNodeId.
* @returns a value of type CP (ComparisonResult). The possible return values are CP.gt (greater than), CP.lt (less
* than), or CP.eq (equal).
*/
protected _compare(a: BinaryTreeNodeId, b: BinaryTreeNodeId): CP {
const compared = this._comparator(a, b);
if (compared > 0) return CP.gt;
else if (compared < 0) return CP.lt;
else return CP.eq;
}
// --- end additional functions
}