mirror of
https://github.com/zrwusa/data-structure-typed.git
synced 2025-01-18 11:14:05 +00:00
fix: Discard the awkward type-safe implementation in the binary tree data structure where subclasses need to pass the node type and tree type back to the parent class.
This commit is contained in:
parent
691fb62893
commit
6dc64dbb53
|
@ -8,7 +8,7 @@ All notable changes to this project will be documented in this file.
|
|||
- [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
|
||||
- [`auto-changelog`](https://github.com/CookPete/auto-changelog)
|
||||
|
||||
## [v1.53.9](https://github.com/zrwusa/data-structure-typed/compare/v1.51.5...main) (upcoming)
|
||||
## [v1.54.0](https://github.com/zrwusa/data-structure-typed/compare/v1.51.5...main) (upcoming)
|
||||
|
||||
### Changes
|
||||
|
||||
|
|
52
package-lock.json
generated
52
package-lock.json
generated
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "data-structure-typed",
|
||||
"version": "1.53.9",
|
||||
"version": "1.54.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "data-structure-typed",
|
||||
"version": "1.53.9",
|
||||
"version": "1.54.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^1.2.2",
|
||||
|
@ -19,11 +19,11 @@
|
|||
"@typescript-eslint/eslint-plugin": "^8.12.1",
|
||||
"@typescript-eslint/parser": "^8.12.1",
|
||||
"auto-changelog": "^2.5.0",
|
||||
"avl-tree-typed": "^1.53.8",
|
||||
"avl-tree-typed": "^1.54.0",
|
||||
"benchmark": "^2.1.4",
|
||||
"binary-tree-typed": "^1.53.8",
|
||||
"bst-typed": "^1.53.8",
|
||||
"data-structure-typed": "^1.53.8",
|
||||
"binary-tree-typed": "^1.54.0",
|
||||
"bst-typed": "^1.54.0",
|
||||
"data-structure-typed": "^1.54.0",
|
||||
"dependency-cruiser": "^16.5.0",
|
||||
"doctoc": "^2.2.1",
|
||||
"eslint": "^9.13.0",
|
||||
|
@ -32,7 +32,7 @@
|
|||
"eslint-import-resolver-typescript": "^3.6.3",
|
||||
"eslint-plugin-import": "^2.31.0",
|
||||
"fast-glob": "^3.3.2",
|
||||
"heap-typed": "^1.53.8",
|
||||
"heap-typed": "^1.54.0",
|
||||
"istanbul-badges-readme": "^1.9.0",
|
||||
"jest": "^29.7.0",
|
||||
"js-sdsl": "^4.4.2",
|
||||
|
@ -3437,13 +3437,13 @@
|
|||
}
|
||||
},
|
||||
"node_modules/avl-tree-typed": {
|
||||
"version": "1.53.8",
|
||||
"resolved": "https://registry.npmjs.org/avl-tree-typed/-/avl-tree-typed-1.53.8.tgz",
|
||||
"integrity": "sha512-FJKmj/kYbdK7Du/Bva9NSLHmiSVA4KqV7AEd4yqnKYrwEfXVfvHJ6wggfyQmdwhrygFTET4ByAldshFzGIwBHQ==",
|
||||
"version": "1.54.0",
|
||||
"resolved": "https://registry.npmjs.org/avl-tree-typed/-/avl-tree-typed-1.54.0.tgz",
|
||||
"integrity": "sha512-MKPtDs1yhtlf/5zd2ObkIk7LvpCoCfCljz0b2TNiy28HUiwcbLUsbdbKu40UWEvNxQyqATiN4cJdmkdzL9ExPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"data-structure-typed": "^1.53.8"
|
||||
"data-structure-typed": "^1.54.0"
|
||||
}
|
||||
},
|
||||
"node_modules/babel-jest": {
|
||||
|
@ -3602,13 +3602,13 @@
|
|||
}
|
||||
},
|
||||
"node_modules/binary-tree-typed": {
|
||||
"version": "1.53.8",
|
||||
"resolved": "https://registry.npmjs.org/binary-tree-typed/-/binary-tree-typed-1.53.8.tgz",
|
||||
"integrity": "sha512-qMTzw2MfEB1Ihn5LBtmgk4bL5rBd0E6x1bJLiZTudbWv/PrDrT+GrtIcVozwKQG6QwjRbbnnkWYDm509l+To3g==",
|
||||
"version": "1.54.0",
|
||||
"resolved": "https://registry.npmjs.org/binary-tree-typed/-/binary-tree-typed-1.54.0.tgz",
|
||||
"integrity": "sha512-O21INGCCZpW784GDaw9J/GAEo8/IfZ/UJR0B6bK8GHm9g4d9UvMqvWG3Yss4OmMnrZRmRNbbKrx/uzNwjRwPCg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"data-structure-typed": "^1.53.8"
|
||||
"data-structure-typed": "^1.54.0"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
|
@ -3691,13 +3691,13 @@
|
|||
}
|
||||
},
|
||||
"node_modules/bst-typed": {
|
||||
"version": "1.53.8",
|
||||
"resolved": "https://registry.npmjs.org/bst-typed/-/bst-typed-1.53.8.tgz",
|
||||
"integrity": "sha512-BvqI2skHCrPYE3JYhSpSjpsRwGHQKw9/SNE5vC4AzxOQpL3fmg9bSBG5aGIrPk4Uc3BEkL9NUignLbjJMNwXcw==",
|
||||
"version": "1.54.0",
|
||||
"resolved": "https://registry.npmjs.org/bst-typed/-/bst-typed-1.54.0.tgz",
|
||||
"integrity": "sha512-/3S/ijw6syQ66raRBjkuFcSLKOpJ8OOr409+go52fJ+QLMqBRUUb2CBbHHKN3KD65JXoTM+bLd6TzOsquaA8CQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"data-structure-typed": "^1.53.8"
|
||||
"data-structure-typed": "^1.54.0"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-from": {
|
||||
|
@ -4069,9 +4069,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/data-structure-typed": {
|
||||
"version": "1.53.8",
|
||||
"resolved": "https://registry.npmjs.org/data-structure-typed/-/data-structure-typed-1.53.8.tgz",
|
||||
"integrity": "sha512-d0kCsb0U1kNMNcsoJI2zX1LkrsiX9FSLXPN4PL9IweyvAsQybcwdV7Y48ZLcUPWnShipuvaaxFLYtznjNcSsqw==",
|
||||
"version": "1.54.0",
|
||||
"resolved": "https://registry.npmjs.org/data-structure-typed/-/data-structure-typed-1.54.0.tgz",
|
||||
"integrity": "sha512-arcHv2vHwFLElHpavuVp4RpGyjGp0aDjWD+zp1G3UXYjKVBR38NPtFGmPn8BCUnqEElhtmu3HBss6edOzrdKkg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
|
@ -5946,13 +5946,13 @@
|
|||
}
|
||||
},
|
||||
"node_modules/heap-typed": {
|
||||
"version": "1.53.8",
|
||||
"resolved": "https://registry.npmjs.org/heap-typed/-/heap-typed-1.53.8.tgz",
|
||||
"integrity": "sha512-Gmwpyl0JSZka8KMR6q3OMsrfA88XA8BmP3aEdT26UnMsX5HBwlBnj2vJvKqOCl5lPl3AhOD5nAj5zxI84bwrrw==",
|
||||
"version": "1.54.0",
|
||||
"resolved": "https://registry.npmjs.org/heap-typed/-/heap-typed-1.54.0.tgz",
|
||||
"integrity": "sha512-eVkfZSx1Kf5IzVltLFybgVHzcTJL0i9CsgZFHfDSpVTUe3tZ2i/mzCh00olslFsoO5KqmodPaqK3epoUUyEMsw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"data-structure-typed": "^1.53.8"
|
||||
"data-structure-typed": "^1.54.0"
|
||||
}
|
||||
},
|
||||
"node_modules/html-escaper": {
|
||||
|
|
14
package.json
14
package.json
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "data-structure-typed",
|
||||
"version": "1.53.9",
|
||||
"version": "1.54.0",
|
||||
"description": "Javascript Data Structure. Heap, Binary Tree, Red Black Tree, Linked List, Deque, Trie, HashMap, Directed Graph, Undirected Graph, Binary Search Tree(BST), AVL Tree, Priority Queue, Graph, Queue, Tree Multiset, Singly Linked List, Doubly Linked List, Max Heap, Max Priority Queue, Min Heap, Min Priority Queue, Stack. Benchmark compared with C++ STL. API aligned with ES6 and Java.util. Usability is comparable to Python",
|
||||
"main": "dist/cjs/index.js",
|
||||
"module": "dist/mjs/index.js",
|
||||
|
@ -23,7 +23,7 @@
|
|||
"gen:examples": "ts-node scripts/testToExample.ts",
|
||||
"test:in-band": "jest --runInBand",
|
||||
"test": "npm run test:in-band",
|
||||
"test:integration": "npm run update:subs && jest --config jest.integration.config.js",
|
||||
"test:integration": "npm run update:subs && jest --config jest.integration.config.js && tsc test/integration/compile.ts",
|
||||
"test:perf": "npm run build:cjs && npm run build:mjs && ts-node test/performance/reportor.ts",
|
||||
"check": "tsc --noEmit",
|
||||
"check:circular-refs": "dependency-cruiser src",
|
||||
|
@ -70,11 +70,11 @@
|
|||
"@typescript-eslint/eslint-plugin": "^8.12.1",
|
||||
"@typescript-eslint/parser": "^8.12.1",
|
||||
"auto-changelog": "^2.5.0",
|
||||
"avl-tree-typed": "^1.53.8",
|
||||
"avl-tree-typed": "^1.54.0",
|
||||
"benchmark": "^2.1.4",
|
||||
"binary-tree-typed": "^1.53.8",
|
||||
"bst-typed": "^1.53.8",
|
||||
"data-structure-typed": "^1.53.8",
|
||||
"binary-tree-typed": "^1.54.0",
|
||||
"bst-typed": "^1.54.0",
|
||||
"data-structure-typed": "^1.54.0",
|
||||
"dependency-cruiser": "^16.5.0",
|
||||
"doctoc": "^2.2.1",
|
||||
"eslint": "^9.13.0",
|
||||
|
@ -83,7 +83,7 @@
|
|||
"eslint-import-resolver-typescript": "^3.6.3",
|
||||
"eslint-plugin-import": "^2.31.0",
|
||||
"fast-glob": "^3.3.2",
|
||||
"heap-typed": "^1.53.8",
|
||||
"heap-typed": "^1.54.0",
|
||||
"istanbul-badges-readme": "^1.9.0",
|
||||
"jest": "^29.7.0",
|
||||
"js-sdsl": "^4.4.2",
|
||||
|
|
|
@ -6,23 +6,18 @@
|
|||
* @license MIT License
|
||||
*/
|
||||
import type {
|
||||
AVLTreeMultiMapNested,
|
||||
AVLTreeMultiMapNodeNested,
|
||||
AVLTreeMultiMapOptions,
|
||||
BinaryTreeDeleteResult,
|
||||
BSTNOptKeyOrNode,
|
||||
BTNRep,
|
||||
EntryCallback,
|
||||
IterationType
|
||||
IterationType,
|
||||
OptNodeOrNull
|
||||
} from '../../types';
|
||||
import { IBinaryTree } from '../../interfaces';
|
||||
import { AVLTree, AVLTreeNode } from './avl-tree';
|
||||
|
||||
export class AVLTreeMultiMapNode<
|
||||
K = any,
|
||||
V = any,
|
||||
NODE extends AVLTreeMultiMapNode<K, V, NODE> = AVLTreeMultiMapNodeNested<K, V>
|
||||
> extends AVLTreeNode<K, V, NODE> {
|
||||
export class AVLTreeMultiMapNode<K = any, V = any> extends AVLTreeNode<K, V> {
|
||||
/**
|
||||
* The constructor function initializes a BinaryTreeNode object with a key, value, and count.
|
||||
* @param {K} key - The `key` parameter is of type `K` and represents the unique identifier
|
||||
|
@ -37,32 +32,42 @@ export class AVLTreeMultiMapNode<
|
|||
super(key, value);
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
override parent?: AVLTreeMultiMapNode<K, V> = undefined;
|
||||
|
||||
override _left?: OptNodeOrNull<AVLTreeMultiMapNode<K, V>> = undefined;
|
||||
|
||||
override get left(): OptNodeOrNull<AVLTreeMultiMapNode<K, V>> {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
override set left(v: OptNodeOrNull<AVLTreeMultiMapNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this;
|
||||
}
|
||||
this._left = v;
|
||||
}
|
||||
|
||||
override _right?: OptNodeOrNull<AVLTreeMultiMapNode<K, V>> = undefined;
|
||||
|
||||
override get right(): OptNodeOrNull<AVLTreeMultiMapNode<K, V>> {
|
||||
return this._right;
|
||||
}
|
||||
|
||||
override set right(v: OptNodeOrNull<AVLTreeMultiMapNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this;
|
||||
}
|
||||
this._right = v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The only distinction between a AVLTreeMultiMap and a AVLTree lies in the ability of the former to store duplicate nodes through the utilization of counters.
|
||||
*/
|
||||
export class AVLTreeMultiMap<
|
||||
K = any,
|
||||
V = any,
|
||||
R = object,
|
||||
MK = any,
|
||||
MV = any,
|
||||
MR = object,
|
||||
NODE extends AVLTreeMultiMapNode<K, V, NODE> = AVLTreeMultiMapNode<K, V, AVLTreeMultiMapNodeNested<K, V>>,
|
||||
TREE extends AVLTreeMultiMap<K, V, R, MK, MV, MR, NODE, TREE> = AVLTreeMultiMap<
|
||||
K,
|
||||
V,
|
||||
R,
|
||||
MK,
|
||||
MV,
|
||||
MR,
|
||||
NODE,
|
||||
AVLTreeMultiMapNested<K, V, R, MK, MV, MR, NODE>
|
||||
>
|
||||
>
|
||||
extends AVLTree<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
export class AVLTreeMultiMap<K = any, V = any, R = object, MK = any, MV = any, MR = object>
|
||||
extends AVLTree<K, V, R, MK, MV, MR>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR>
|
||||
{
|
||||
/**
|
||||
* The constructor initializes a new AVLTreeMultiMap object with optional initial elements.
|
||||
|
@ -73,7 +78,7 @@ export class AVLTreeMultiMap<
|
|||
* `compareValues` functions to define custom comparison logic for keys and values, respectively.
|
||||
*/
|
||||
constructor(
|
||||
keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, NODE>> = [],
|
||||
keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, AVLTreeMultiMapNode<K, V>>> = [],
|
||||
options?: AVLTreeMultiMapOptions<K, V, R>
|
||||
) {
|
||||
super([], options);
|
||||
|
@ -114,10 +119,10 @@ export class AVLTreeMultiMap<
|
|||
* @param {number} [count] - The `count` parameter represents the number of occurrences of a
|
||||
* key-value pair in the AVLTreeMultiMapNode. It is an optional parameter, so it can be omitted when
|
||||
* calling the `createNode` method. If provided, it specifies the initial count for the node.
|
||||
* @returns a new instance of the AVLTreeMultiMapNode class, casted as NODE.
|
||||
* @returns a new instance of the AVLTreeMultiMapNode class, casted as AVLTreeMultiMapNode<K, V>.
|
||||
*/
|
||||
override createNode(key: K, value?: V, count?: number): NODE {
|
||||
return new AVLTreeMultiMapNode(key, this._isMapMode ? undefined : value, count) as NODE;
|
||||
override createNode(key: K, value?: V, count?: number): AVLTreeMultiMapNode<K, V> {
|
||||
return new AVLTreeMultiMapNode(key, this._isMapMode ? undefined : value, count) as AVLTreeMultiMapNode<K, V>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -127,25 +132,27 @@ export class AVLTreeMultiMap<
|
|||
* @returns a new instance of the AVLTreeMultiMap class, with the specified options, as a TREE
|
||||
* object.
|
||||
*/
|
||||
override createTree(options?: AVLTreeMultiMapOptions<K, V, R>): TREE {
|
||||
return new AVLTreeMultiMap<K, V, R, MK, MV, MR, NODE, TREE>([], {
|
||||
override createTree(options?: AVLTreeMultiMapOptions<K, V, R>) {
|
||||
return new AVLTreeMultiMap<K, V, R, MK, MV, MR>([], {
|
||||
iterationType: this.iterationType,
|
||||
isMapMode: this._isMapMode,
|
||||
specifyComparable: this._specifyComparable,
|
||||
toEntryFn: this._toEntryFn,
|
||||
isReverse: this._isReverse,
|
||||
...options
|
||||
}) as TREE;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The function checks if the input is an instance of AVLTreeMultiMapNode.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, AVLTreeMultiMapNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, AVLTreeMultiMapNode<K, V>>`.
|
||||
* @returns a boolean value indicating whether the input parameter `keyNodeEntryOrRaw` is
|
||||
* an instance of the `AVLTreeMultiMapNode` class.
|
||||
*/
|
||||
override isNode(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R): keyNodeEntryOrRaw is NODE {
|
||||
override isNode(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, AVLTreeMultiMapNode<K, V>> | R
|
||||
): keyNodeEntryOrRaw is AVLTreeMultiMapNode<K, V> {
|
||||
return keyNodeEntryOrRaw instanceof AVLTreeMultiMapNode;
|
||||
}
|
||||
|
||||
|
@ -155,9 +162,9 @@ export class AVLTreeMultiMap<
|
|||
*
|
||||
* The function overrides the add method of a TypeScript class to add a new node to a data structure
|
||||
* and update the count.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The
|
||||
* @param {BTNRep<K, V, AVLTreeMultiMapNode<K, V>> | R} keyNodeEntryOrRaw - The
|
||||
* `keyNodeEntryOrRaw` parameter can accept a value of type `R`, which can be any type. It
|
||||
* can also accept a value of type `BTNRep<K, V, NODE>`, which represents a key, node,
|
||||
* can also accept a value of type `BTNRep<K, V, AVLTreeMultiMapNode<K, V>>`, which represents a key, node,
|
||||
* entry, or raw element
|
||||
* @param {V} [value] - The `value` parameter represents the value associated with the key in the
|
||||
* data structure. It is an optional parameter, so it can be omitted if not needed.
|
||||
|
@ -166,7 +173,7 @@ export class AVLTreeMultiMap<
|
|||
* be added once. However, you can specify a different value for `count` if you want to add
|
||||
* @returns a boolean value.
|
||||
*/
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R, value?: V, count = 1): boolean {
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, AVLTreeMultiMapNode<K, V>> | R, value?: V, count = 1): boolean {
|
||||
const [newNode, newValue] = this._keyValueNodeEntryRawToNodeAndValue(keyNodeEntryOrRaw, value, count);
|
||||
if (newNode === undefined) return false;
|
||||
|
||||
|
@ -184,7 +191,7 @@ export class AVLTreeMultiMap<
|
|||
*
|
||||
* The function overrides the delete method in a binary tree data structure, handling deletion of
|
||||
* nodes and maintaining balance in the tree.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The `predicate`
|
||||
* @param {BTNRep<K, V, AVLTreeMultiMapNode<K, V>> | R} keyNodeEntryOrRaw - The `predicate`
|
||||
* parameter in the `delete` method is used to specify the condition for deleting a node from the
|
||||
* binary tree. It can be a key, node, or entry that determines which
|
||||
* node(s) should be deleted.
|
||||
|
@ -197,16 +204,19 @@ export class AVLTreeMultiMap<
|
|||
* method returns an array of `BinaryTreeDeleteResult` objects, each containing information about the
|
||||
* deleted node and whether balancing is needed in the tree.
|
||||
*/
|
||||
override delete(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R, ignoreCount = false): BinaryTreeDeleteResult<NODE>[] {
|
||||
const deletedResult: BinaryTreeDeleteResult<NODE>[] = [];
|
||||
override delete(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, AVLTreeMultiMapNode<K, V>> | R,
|
||||
ignoreCount = false
|
||||
): BinaryTreeDeleteResult<AVLTreeMultiMapNode<K, V>>[] {
|
||||
const deletedResult: BinaryTreeDeleteResult<AVLTreeMultiMapNode<K, V>>[] = [];
|
||||
if (!this.root) return deletedResult;
|
||||
|
||||
const curr: NODE | undefined = this.getNode(keyNodeEntryOrRaw) ?? undefined;
|
||||
const curr: AVLTreeMultiMapNode<K, V> | undefined = this.getNode(keyNodeEntryOrRaw) ?? undefined;
|
||||
if (!curr) return deletedResult;
|
||||
|
||||
const parent: NODE | undefined = curr?.parent ? curr.parent : undefined;
|
||||
let needBalanced: NODE | undefined = undefined,
|
||||
orgCurrent: NODE | undefined = curr;
|
||||
const parent: AVLTreeMultiMapNode<K, V> | undefined = curr?.parent ? curr.parent : undefined;
|
||||
let needBalanced: AVLTreeMultiMapNode<K, V> | undefined = undefined,
|
||||
orgCurrent: AVLTreeMultiMapNode<K, V> | undefined = curr;
|
||||
|
||||
if (curr.count > 1 && !ignoreCount) {
|
||||
curr.count--;
|
||||
|
@ -324,7 +334,7 @@ export class AVLTreeMultiMap<
|
|||
* The function overrides the clone method to create a deep copy of a tree object.
|
||||
* @returns The `clone()` method is returning a cloned instance of the `TREE` object.
|
||||
*/
|
||||
override clone(): TREE {
|
||||
override clone() {
|
||||
const cloned = this.createTree();
|
||||
if (this._isMapMode) this.bfs(node => cloned.add(node.key, undefined, node.count));
|
||||
else this.bfs(node => cloned.add(node.key, node.value, node.count));
|
||||
|
@ -366,20 +376,20 @@ export class AVLTreeMultiMap<
|
|||
/**
|
||||
* The function `keyValueNodeEntryRawToNodeAndValue` converts a key, value, entry, or raw element into
|
||||
* a node object.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The
|
||||
* `keyNodeEntryOrRaw` parameter can be of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, AVLTreeMultiMapNode<K, V>> | R} keyNodeEntryOrRaw - The
|
||||
* `keyNodeEntryOrRaw` parameter can be of type `R` or `BTNRep<K, V, AVLTreeMultiMapNode<K, V>>`.
|
||||
* @param {V} [value] - The `value` parameter is an optional value that can be passed to the
|
||||
* `override` function. It represents the value associated with the key in the data structure. If no
|
||||
* value is provided, it will default to `undefined`.
|
||||
* @param [count=1] - The `count` parameter is an optional parameter that specifies the number of
|
||||
* times the key-value pair should be added to the data structure. If not provided, it defaults to 1.
|
||||
* @returns either a NODE object or undefined.
|
||||
* @returns either a AVLTreeMultiMapNode<K, V> object or undefined.
|
||||
*/
|
||||
protected override _keyValueNodeEntryRawToNodeAndValue(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R,
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, AVLTreeMultiMapNode<K, V>> | R,
|
||||
value?: V,
|
||||
count = 1
|
||||
): [NODE | undefined, V | undefined] {
|
||||
): [AVLTreeMultiMapNode<K, V> | undefined, V | undefined] {
|
||||
if (keyNodeEntryOrRaw === undefined || keyNodeEntryOrRaw === null) return [undefined, undefined];
|
||||
if (this.isNode(keyNodeEntryOrRaw)) return [keyNodeEntryOrRaw, value];
|
||||
|
||||
|
@ -407,17 +417,17 @@ export class AVLTreeMultiMap<
|
|||
*
|
||||
* The `_swapProperties` function swaps the properties (key, value, count, height) between two nodes
|
||||
* in a binary search tree.
|
||||
* @param {R | BSTNOptKeyOrNode<K, NODE>} srcNode - The `srcNode` parameter represents the source node
|
||||
* @param {R | BSTNOptKeyOrNode<K, AVLTreeMultiMapNode<K, V>>} srcNode - The `srcNode` parameter represents the source node
|
||||
* that will be swapped with the `destNode`.
|
||||
* @param {R | BSTNOptKeyOrNode<K, NODE>} destNode - The `destNode` parameter represents the destination
|
||||
* @param {R | BSTNOptKeyOrNode<K, AVLTreeMultiMapNode<K, V>>} destNode - The `destNode` parameter represents the destination
|
||||
* node where the properties will be swapped with the source node.
|
||||
* @returns The method is returning the `destNode` after swapping its properties with the `srcNode`.
|
||||
* If either `srcNode` or `destNode` is undefined, it returns `undefined`.
|
||||
*/
|
||||
protected override _swapProperties(
|
||||
srcNode: R | BSTNOptKeyOrNode<K, NODE>,
|
||||
destNode: R | BSTNOptKeyOrNode<K, NODE>
|
||||
): NODE | undefined {
|
||||
srcNode: R | BSTNOptKeyOrNode<K, AVLTreeMultiMapNode<K, V>>,
|
||||
destNode: R | BSTNOptKeyOrNode<K, AVLTreeMultiMapNode<K, V>>
|
||||
): AVLTreeMultiMapNode<K, V> | undefined {
|
||||
srcNode = this.ensureNode(srcNode);
|
||||
destNode = this.ensureNode(destNode);
|
||||
if (srcNode && destNode) {
|
||||
|
@ -447,13 +457,16 @@ export class AVLTreeMultiMap<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function replaces an old node with a new node and updates the count property of the new node.
|
||||
* @param {NODE} oldNode - The oldNode parameter represents the node that needs to be replaced in the
|
||||
* data structure. It is of type NODE.
|
||||
* @param {NODE} newNode - The `newNode` parameter is an instance of the `NODE` class.
|
||||
* @param {AVLTreeMultiMapNode<K, V>} oldNode - The oldNode parameter represents the node that needs to be replaced in the
|
||||
* data structure. It is of type AVLTreeMultiMapNode<K, V>.
|
||||
* @param {AVLTreeMultiMapNode<K, V>} newNode - The `newNode` parameter is an instance of the `AVLTreeMultiMapNode<K, V>` class.
|
||||
* @returns The method is returning the result of calling the `_replaceNode` method from the
|
||||
* superclass, which is of type `NODE`.
|
||||
* superclass, which is of type `AVLTreeMultiMapNode<K, V>`.
|
||||
*/
|
||||
protected override _replaceNode(oldNode: NODE, newNode: NODE): NODE {
|
||||
protected override _replaceNode(
|
||||
oldNode: AVLTreeMultiMapNode<K, V>,
|
||||
newNode: AVLTreeMultiMapNode<K, V>
|
||||
): AVLTreeMultiMapNode<K, V> {
|
||||
newNode.count = oldNode.count + newNode.count;
|
||||
return super._replaceNode(oldNode, newNode);
|
||||
}
|
||||
|
|
|
@ -7,21 +7,16 @@
|
|||
*/
|
||||
import { BST, BSTNode } from './bst';
|
||||
import type {
|
||||
AVLTreeNested,
|
||||
AVLTreeNodeNested,
|
||||
AVLTreeOptions,
|
||||
BinaryTreeDeleteResult,
|
||||
BSTNOptKeyOrNode,
|
||||
BTNRep,
|
||||
EntryCallback
|
||||
EntryCallback,
|
||||
OptNodeOrNull
|
||||
} from '../../types';
|
||||
import { IBinaryTree } from '../../interfaces';
|
||||
|
||||
export class AVLTreeNode<
|
||||
K = any,
|
||||
V = any,
|
||||
NODE extends AVLTreeNode<K, V, NODE> = AVLTreeNodeNested<K, V>
|
||||
> extends BSTNode<K, V, NODE> {
|
||||
export class AVLTreeNode<K = any, V = any> extends BSTNode<K, V> {
|
||||
/**
|
||||
* The constructor function initializes a new instance of a class with a key and an optional value,
|
||||
* and sets the height property to 0.
|
||||
|
@ -33,6 +28,34 @@ export class AVLTreeNode<
|
|||
constructor(key: K, value?: V) {
|
||||
super(key, value);
|
||||
}
|
||||
|
||||
override parent?: AVLTreeNode<K, V> = undefined;
|
||||
|
||||
override _left?: OptNodeOrNull<AVLTreeNode<K, V>> = undefined;
|
||||
|
||||
override get left(): OptNodeOrNull<AVLTreeNode<K, V>> {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
override set left(v: OptNodeOrNull<AVLTreeNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this;
|
||||
}
|
||||
this._left = v;
|
||||
}
|
||||
|
||||
override _right?: OptNodeOrNull<AVLTreeNode<K, V>> = undefined;
|
||||
|
||||
override get right(): OptNodeOrNull<AVLTreeNode<K, V>> {
|
||||
return this._right;
|
||||
}
|
||||
|
||||
override set right(v: OptNodeOrNull<AVLTreeNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this;
|
||||
}
|
||||
this._right = v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -44,27 +67,9 @@ export class AVLTreeNode<
|
|||
* 6. Complex Insertions and Deletions: Due to rebalancing, these operations are more complex than in a regular BST.
|
||||
* 7. Path Length: The path length from the root to any leaf is longer compared to an unbalanced BST, but shorter than a linear chain of nodes.
|
||||
*/
|
||||
export class AVLTree<
|
||||
K = any,
|
||||
V = any,
|
||||
R = object,
|
||||
MK = any,
|
||||
MV = any,
|
||||
MR = object,
|
||||
NODE extends AVLTreeNode<K, V, NODE> = AVLTreeNode<K, V, AVLTreeNodeNested<K, V>>,
|
||||
TREE extends AVLTree<K, V, R, MK, MV, MR, NODE, TREE> = AVLTree<
|
||||
K,
|
||||
V,
|
||||
R,
|
||||
MK,
|
||||
MV,
|
||||
MR,
|
||||
NODE,
|
||||
AVLTreeNested<K, V, R, MK, MV, MR, NODE>
|
||||
>
|
||||
>
|
||||
extends BST<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
export class AVLTree<K = any, V = any, R = object, MK = any, MV = any, MR = object>
|
||||
extends BST<K, V, R, MK, MV, MR>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR>
|
||||
{
|
||||
/**
|
||||
* This is a constructor function for an AVLTree class that initializes the tree with keys, nodes,
|
||||
|
@ -77,7 +82,10 @@ export class AVLTree<
|
|||
* keys), `allowDuplicates` (a boolean indicating whether duplicate keys are allowed), and
|
||||
* `nodeBuilder` (
|
||||
*/
|
||||
constructor(keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, NODE>> = [], options?: AVLTreeOptions<K, V, R>) {
|
||||
constructor(
|
||||
keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, AVLTreeNode<K, V>>> = [],
|
||||
options?: AVLTreeOptions<K, V, R>
|
||||
) {
|
||||
super([], options);
|
||||
if (keysNodesEntriesOrRaws) super.addMany(keysNodesEntriesOrRaws);
|
||||
}
|
||||
|
@ -89,10 +97,10 @@ export class AVLTree<
|
|||
* @param {V} [value] - The "value" parameter is an optional parameter of type V. It represents the
|
||||
* value associated with the key in the node being created.
|
||||
* @returns The method is returning a new instance of the AVLTreeNode class, casted as the generic
|
||||
* type NODE.
|
||||
* type AVLTreeNode<K, V>.
|
||||
*/
|
||||
override createNode(key: K, value?: V): NODE {
|
||||
return new AVLTreeNode<K, V, NODE>(key, this._isMapMode ? undefined : value) as NODE;
|
||||
override createNode(key: K, value?: V): AVLTreeNode<K, V> {
|
||||
return new AVLTreeNode<K, V>(key, this._isMapMode ? undefined : value) as AVLTreeNode<K, V>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -102,25 +110,25 @@ export class AVLTree<
|
|||
* being created.
|
||||
* @returns a new AVLTree object.
|
||||
*/
|
||||
override createTree(options?: AVLTreeOptions<K, V, R>): TREE {
|
||||
return new AVLTree<K, V, R, MK, MV, MR, NODE, TREE>([], {
|
||||
override createTree(options?: AVLTreeOptions<K, V, R>) {
|
||||
return new AVLTree<K, V, R, MK, MV, MR>([], {
|
||||
iterationType: this.iterationType,
|
||||
isMapMode: this._isMapMode,
|
||||
specifyComparable: this._specifyComparable,
|
||||
toEntryFn: this._toEntryFn,
|
||||
isReverse: this._isReverse,
|
||||
...options
|
||||
}) as TREE;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The function checks if the input is an instance of AVLTreeNode.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, AVLTreeNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, AVLTreeNode<K, V>>`.
|
||||
* @returns a boolean value indicating whether the input parameter `keyNodeEntryOrRaw` is
|
||||
* an instance of the `AVLTreeNode` class.
|
||||
*/
|
||||
override isNode(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R): keyNodeEntryOrRaw is NODE {
|
||||
override isNode(keyNodeEntryOrRaw: BTNRep<K, V, AVLTreeNode<K, V>> | R): keyNodeEntryOrRaw is AVLTreeNode<K, V> {
|
||||
return keyNodeEntryOrRaw instanceof AVLTreeNode;
|
||||
}
|
||||
|
||||
|
@ -130,14 +138,14 @@ export class AVLTree<
|
|||
*
|
||||
* The function overrides the add method of a class and inserts a key-value pair into a data
|
||||
* structure, then balances the path.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can accept values of type `R`, `BTNRep<K, V, NODE>`, or
|
||||
* @param {BTNRep<K, V, AVLTreeNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can accept values of type `R`, `BTNRep<K, V, AVLTreeNode<K, V>>`, or
|
||||
* `RawElement`.
|
||||
* @param {V} [value] - The `value` parameter is an optional value that you want to associate with
|
||||
* the key or node being added to the data structure.
|
||||
* @returns The method is returning a boolean value.
|
||||
*/
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R, value?: V): boolean {
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, AVLTreeNode<K, V>> | R, value?: V): boolean {
|
||||
if (keyNodeEntryOrRaw === null) return false;
|
||||
const inserted = super.add(keyNodeEntryOrRaw, value);
|
||||
if (inserted) this._balancePath(keyNodeEntryOrRaw);
|
||||
|
@ -150,14 +158,14 @@ export class AVLTree<
|
|||
*
|
||||
* The function overrides the delete method in a TypeScript class, performs deletion, and then
|
||||
* balances the tree if necessary.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The `keyNodeEntryOrRaw`
|
||||
* @param {BTNRep<K, V, AVLTreeNode<K, V>> | R} keyNodeEntryOrRaw - The `keyNodeEntryOrRaw`
|
||||
* parameter in the `override delete` method can be one of the following types:
|
||||
* @returns The `delete` method is being overridden in this code snippet. It first calls the `delete`
|
||||
* method from the superclass (presumably a parent class) with the provided `predicate`, which could
|
||||
* be a key, node, entry, or a custom predicate. The result of this deletion operation is stored in
|
||||
* `deletedResults`, which is an array of `BinaryTreeDeleteResult` objects.
|
||||
*/
|
||||
override delete(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R): BinaryTreeDeleteResult<NODE>[] {
|
||||
override delete(keyNodeEntryOrRaw: BTNRep<K, V, AVLTreeNode<K, V>> | R): BinaryTreeDeleteResult<AVLTreeNode<K, V>>[] {
|
||||
const deletedResults = super.delete(keyNodeEntryOrRaw);
|
||||
for (const { needBalanced } of deletedResults) {
|
||||
if (needBalanced) {
|
||||
|
@ -180,23 +188,29 @@ export class AVLTree<
|
|||
return newTree;
|
||||
}
|
||||
|
||||
override clone() {
|
||||
const cloned = this.createTree();
|
||||
this._clone(cloned);
|
||||
return cloned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time Complexity: O(1)
|
||||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `_swapProperties` function swaps the key, value, and height properties between two nodes in a
|
||||
* binary search tree.
|
||||
* @param {R | BSTNOptKeyOrNode<K, NODE>} srcNode - The `srcNode` parameter represents either a node
|
||||
* object (`NODE`) or a key-value pair (`R`) that is being swapped with another node.
|
||||
* @param {R | BSTNOptKeyOrNode<K, NODE>} destNode - The `destNode` parameter is either an instance of
|
||||
* `R` or an instance of `BSTNOptKeyOrNode<K, NODE>`.
|
||||
* @param {R | BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>} srcNode - The `srcNode` parameter represents either a node
|
||||
* object (`AVLTreeNode<K, V>`) or a key-value pair (`R`) that is being swapped with another node.
|
||||
* @param {R | BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>} destNode - The `destNode` parameter is either an instance of
|
||||
* `R` or an instance of `BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>`.
|
||||
* @returns The method is returning the `destNodeEnsured` object if both `srcNodeEnsured` and
|
||||
* `destNodeEnsured` are truthy. Otherwise, it returns `undefined`.
|
||||
*/
|
||||
protected override _swapProperties(
|
||||
srcNode: R | BSTNOptKeyOrNode<K, NODE>,
|
||||
destNode: R | BSTNOptKeyOrNode<K, NODE>
|
||||
): NODE | undefined {
|
||||
srcNode: R | BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>,
|
||||
destNode: R | BSTNOptKeyOrNode<K, AVLTreeNode<K, V>>
|
||||
): AVLTreeNode<K, V> | undefined {
|
||||
const srcNodeEnsured = this.ensureNode(srcNode);
|
||||
const destNodeEnsured = this.ensureNode(destNode);
|
||||
|
||||
|
@ -226,12 +240,12 @@ export class AVLTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function calculates the balance factor of a node in a binary tree.
|
||||
* @param {NODE} node - The parameter "node" is of type "NODE", which likely represents a node in a
|
||||
* @param {AVLTreeNode<K, V>} node - The parameter "node" is of type "AVLTreeNode<K, V>", which likely represents a node in a
|
||||
* binary tree data structure.
|
||||
* @returns the balance factor of a given node. The balance factor is calculated by subtracting the
|
||||
* height of the left subtree from the height of the right subtree.
|
||||
*/
|
||||
protected _balanceFactor(node: NODE): number {
|
||||
protected _balanceFactor(node: AVLTreeNode<K, V>): number {
|
||||
if (!node.right)
|
||||
// node has no right subtree
|
||||
return -node.height;
|
||||
|
@ -247,9 +261,9 @@ export class AVLTree<
|
|||
*
|
||||
* The function updates the height of a node in a binary tree based on the heights of its left and
|
||||
* right children.
|
||||
* @param {NODE} node - The parameter "node" represents a node in a binary tree data structure.
|
||||
* @param {AVLTreeNode<K, V>} node - The parameter "node" represents a node in a binary tree data structure.
|
||||
*/
|
||||
protected _updateHeight(node: NODE): void {
|
||||
protected _updateHeight(node: AVLTreeNode<K, V>): void {
|
||||
if (!node.left && !node.right) node.height = 0;
|
||||
else if (!node.left) {
|
||||
const rightHeight = node.right ? node.right.height : 0;
|
||||
|
@ -263,9 +277,9 @@ export class AVLTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `_balanceLL` function performs a left-left rotation to balance a binary search tree.
|
||||
* @param {NODE} A - A is a node in a binary tree.
|
||||
* @param {AVLTreeNode<K, V>} A - A is a node in a binary tree.
|
||||
*/
|
||||
protected _balanceLL(A: NODE): void {
|
||||
protected _balanceLL(A: AVLTreeNode<K, V>): void {
|
||||
const parentOfA = A.parent;
|
||||
const B = A.left;
|
||||
if (B !== null) A.parent = B;
|
||||
|
@ -296,9 +310,9 @@ export class AVLTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `_balanceLR` function performs a left-right rotation to balance a binary tree.
|
||||
* @param {NODE} A - A is a node in a binary tree.
|
||||
* @param {AVLTreeNode<K, V>} A - A is a node in a binary tree.
|
||||
*/
|
||||
protected _balanceLR(A: NODE): void {
|
||||
protected _balanceLR(A: AVLTreeNode<K, V>): void {
|
||||
const parentOfA = A.parent;
|
||||
const B = A.left;
|
||||
let C = undefined;
|
||||
|
@ -347,9 +361,9 @@ export class AVLTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function `_balanceRR` performs a right-right rotation to balance a binary tree.
|
||||
* @param {NODE} A - A is a node in a binary tree.
|
||||
* @param {AVLTreeNode<K, V>} A - A is a node in a binary tree.
|
||||
*/
|
||||
protected _balanceRR(A: NODE): void {
|
||||
protected _balanceRR(A: AVLTreeNode<K, V>): void {
|
||||
const parentOfA = A.parent;
|
||||
const B = A.right;
|
||||
if (B !== null) A.parent = B;
|
||||
|
@ -385,9 +399,9 @@ export class AVLTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function `_balanceRL` performs a right-left rotation to balance a binary tree.
|
||||
* @param {NODE} A - A is a node in a binary tree.
|
||||
* @param {AVLTreeNode<K, V>} A - A is a node in a binary tree.
|
||||
*/
|
||||
protected _balanceRL(A: NODE): void {
|
||||
protected _balanceRL(A: AVLTreeNode<K, V>): void {
|
||||
const parentOfA = A.parent;
|
||||
const B = A.right;
|
||||
let C = undefined;
|
||||
|
@ -436,10 +450,10 @@ export class AVLTree<
|
|||
*
|
||||
* The `_balancePath` function is used to update the heights of nodes and perform rotation operations
|
||||
* to restore balance in an AVL tree after inserting a node.
|
||||
* @param {BTNRep<K, V, NODE> | R} node - The `node` parameter can be of type `R` or
|
||||
* `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, AVLTreeNode<K, V>> | R} node - The `node` parameter can be of type `R` or
|
||||
* `BTNRep<K, V, AVLTreeNode<K, V>>`.
|
||||
*/
|
||||
protected _balancePath(node: BTNRep<K, V, NODE> | R): void {
|
||||
protected _balancePath(node: BTNRep<K, V, AVLTreeNode<K, V>> | R): void {
|
||||
node = this.ensureNode(node);
|
||||
const path = this.getPathToRoot(node, node => node, false); // first O(log n) + O(log n)
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
|
@ -487,14 +501,14 @@ export class AVLTree<
|
|||
*
|
||||
* The function replaces an old node with a new node and sets the height of the new node to be the
|
||||
* same as the old node.
|
||||
* @param {NODE} oldNode - The `oldNode` parameter represents the node that needs to be replaced in
|
||||
* @param {AVLTreeNode<K, V>} oldNode - The `oldNode` parameter represents the node that needs to be replaced in
|
||||
* the data structure.
|
||||
* @param {NODE} newNode - The `newNode` parameter is the new node that will replace the `oldNode` in
|
||||
* @param {AVLTreeNode<K, V>} newNode - The `newNode` parameter is the new node that will replace the `oldNode` in
|
||||
* the data structure.
|
||||
* @returns The method is returning the result of calling the `_replaceNode` method from the
|
||||
* superclass, with the `oldNode` and `newNode` as arguments.
|
||||
*/
|
||||
protected override _replaceNode(oldNode: NODE, newNode: NODE): NODE {
|
||||
protected override _replaceNode(oldNode: AVLTreeNode<K, V>, newNode: AVLTreeNode<K, V>): AVLTreeNode<K, V> {
|
||||
newNode.height = oldNode.height;
|
||||
|
||||
return super._replaceNode(oldNode, newNode);
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -5,9 +5,7 @@
|
|||
* @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
|
||||
* @license MIT License
|
||||
*/
|
||||
import {
|
||||
BSTNested,
|
||||
BSTNodeNested,
|
||||
import type {
|
||||
BSTNOptKeyOrNode,
|
||||
BSTOptions,
|
||||
BTNRep,
|
||||
|
@ -28,61 +26,35 @@ import { Queue } from '../queue';
|
|||
import { isComparable } from '../../utils';
|
||||
import { Range } from '../../common';
|
||||
|
||||
export class BSTNode<K = any, V = any, NODE extends BSTNode<K, V, NODE> = BSTNodeNested<K, V>> extends BinaryTreeNode<
|
||||
K,
|
||||
V,
|
||||
NODE
|
||||
> {
|
||||
override parent?: NODE;
|
||||
|
||||
export class BSTNode<K = any, V = any> extends BinaryTreeNode<K, V> {
|
||||
constructor(key: K, value?: V) {
|
||||
super(key, value);
|
||||
this.parent = undefined;
|
||||
this._left = undefined;
|
||||
this._right = undefined;
|
||||
}
|
||||
|
||||
override _left?: OptNodeOrNull<NODE>;
|
||||
override parent?: BSTNode<K, V> = undefined;
|
||||
|
||||
/**
|
||||
* The function returns the value of the `_left` property.
|
||||
* @returns The `_left` property of the current object is being returned.
|
||||
*/
|
||||
override get left(): OptNodeOrNull<NODE> {
|
||||
override _left?: OptNodeOrNull<BSTNode<K, V>> = undefined;
|
||||
|
||||
override get left(): OptNodeOrNull<BSTNode<K, V>> {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function sets the left child of a node and updates the parent reference of the child.
|
||||
* @param {OptNode<NODE>} v - The parameter `v` is of type `OptNode<NODE>`. It can either be an
|
||||
* instance of the `NODE` class or `undefined`.
|
||||
*/
|
||||
override set left(v: OptNodeOrNull<NODE>) {
|
||||
override set left(v: OptNodeOrNull<BSTNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this as unknown as NODE;
|
||||
v.parent = this;
|
||||
}
|
||||
this._left = v;
|
||||
}
|
||||
|
||||
override _right?: OptNodeOrNull<NODE>;
|
||||
override _right?: OptNodeOrNull<BSTNode<K, V>> = undefined;
|
||||
|
||||
/**
|
||||
* The function returns the right node of a binary tree or undefined if there is no right node.
|
||||
* @returns The method is returning the value of the `_right` property, which is of type `NODE` or
|
||||
* `undefined`.
|
||||
*/
|
||||
override get right(): OptNodeOrNull<NODE> {
|
||||
override get right(): OptNodeOrNull<BSTNode<K, V>> {
|
||||
return this._right;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function sets the right child of a node and updates the parent reference of the child.
|
||||
* @param {OptNode<NODE>} v - The parameter `v` is of type `OptNode<NODE>`. It can either be a
|
||||
* `NODE` object or `undefined`.
|
||||
*/
|
||||
override set right(v: OptNodeOrNull<NODE>) {
|
||||
override set right(v: OptNodeOrNull<BSTNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this as unknown as NODE;
|
||||
v.parent = this;
|
||||
}
|
||||
this._right = v;
|
||||
}
|
||||
|
@ -153,27 +125,9 @@ export class BSTNode<K = any, V = any, NODE extends BSTNode<K, V, NODE> = BSTNod
|
|||
* console.log(findLCA(5, 35)); // 15
|
||||
* console.log(findLCA(20, 30)); // 25
|
||||
*/
|
||||
export class BST<
|
||||
K = any,
|
||||
V = any,
|
||||
R = object,
|
||||
MK = any,
|
||||
MV = any,
|
||||
MR = object,
|
||||
NODE extends BSTNode<K, V, NODE> = BSTNode<K, V, BSTNodeNested<K, V>>,
|
||||
TREE extends BST<K, V, R, MK, MV, MR, NODE, TREE> = BST<
|
||||
K,
|
||||
V,
|
||||
R,
|
||||
MK,
|
||||
MV,
|
||||
MR,
|
||||
NODE,
|
||||
BSTNested<K, V, R, MK, MV, MR, NODE>
|
||||
>
|
||||
>
|
||||
extends BinaryTree<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
export class BST<K = any, V = any, R = object, MK = any, MV = any, MR = object>
|
||||
extends BinaryTree<K, V, R, MK, MV, MR>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR>
|
||||
{
|
||||
/**
|
||||
* This is the constructor function for a Binary Search Tree class in TypeScript.
|
||||
|
@ -183,7 +137,7 @@ export class BST<
|
|||
* @param [options] - An optional object that contains additional options for the Binary Search Tree.
|
||||
* It can include a comparator function that defines the order of the elements in the tree.
|
||||
*/
|
||||
constructor(keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, NODE>> = [], options?: BSTOptions<K, V, R>) {
|
||||
constructor(keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, BSTNode<K, V>>> = [], options?: BSTOptions<K, V, R>) {
|
||||
super([], options);
|
||||
|
||||
if (options) {
|
||||
|
@ -195,13 +149,13 @@ export class BST<
|
|||
if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);
|
||||
}
|
||||
|
||||
protected override _root?: NODE = undefined;
|
||||
protected override _root?: BSTNode<K, V> = undefined;
|
||||
|
||||
/**
|
||||
* The function returns the root node of a tree structure.
|
||||
* @returns The `_root` property of the object, which is of type `NODE` or `undefined`.
|
||||
* @returns The `_root` property of the object, which is of type `BSTNode<K, V>` or `undefined`.
|
||||
*/
|
||||
override get root(): OptNode<NODE> {
|
||||
override get root(): OptNode<BSTNode<K, V>> {
|
||||
return this._root;
|
||||
}
|
||||
|
||||
|
@ -216,16 +170,55 @@ export class BST<
|
|||
return this._isReverse;
|
||||
}
|
||||
|
||||
protected _comparator: Comparator<K> = (a: K, b: K): number => {
|
||||
if (isComparable(a) && isComparable(b)) {
|
||||
if (a > b) return 1;
|
||||
if (a < b) return -1;
|
||||
return 0;
|
||||
}
|
||||
if (this._specifyComparable) {
|
||||
if (this._specifyComparable(a) > this._specifyComparable(b)) return 1;
|
||||
if (this._specifyComparable(a) < this._specifyComparable(b)) return -1;
|
||||
return 0;
|
||||
}
|
||||
if (typeof a === 'object' || typeof b === 'object') {
|
||||
throw TypeError(
|
||||
`When comparing object types, a custom specifyComparable must be defined in the constructor's options parameter.`
|
||||
);
|
||||
}
|
||||
|
||||
return 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* The function returns the value of the _comparator property.
|
||||
* @returns The `_comparator` property is being returned.
|
||||
*/
|
||||
get comparator() {
|
||||
return this._comparator;
|
||||
}
|
||||
|
||||
protected _specifyComparable?: (key: K) => Comparable;
|
||||
|
||||
/**
|
||||
* This function returns the value of the `_specifyComparable` property.
|
||||
* @returns The method `specifyComparable()` is being returned, which is a getter method for the
|
||||
* `_specifyComparable` property.
|
||||
*/
|
||||
get specifyComparable() {
|
||||
return this._specifyComparable;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function creates a new BSTNode with the given key and value and returns it.
|
||||
* @param {K} key - The key parameter is of type K, which represents the type of the key for the node
|
||||
* being created.
|
||||
* @param {V} [value] - The "value" parameter is an optional parameter of type V. It represents the
|
||||
* value associated with the key in the node being created.
|
||||
* @returns The method is returning a new instance of the BSTNode class, casted as the NODE type.
|
||||
* @returns The method is returning a new instance of the BSTNode class, casted as the BSTNode<K, V> type.
|
||||
*/
|
||||
override createNode(key: K, value?: V): NODE {
|
||||
return new BSTNode<K, V, NODE>(key, this._isMapMode ? undefined : value) as NODE;
|
||||
override createNode(key: K, value?: V): BSTNode<K, V> {
|
||||
return new BSTNode<K, V>(key, this._isMapMode ? undefined : value) as BSTNode<K, V>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -235,33 +228,15 @@ export class BST<
|
|||
* following properties:
|
||||
* @returns a new instance of the BST class with the provided options.
|
||||
*/
|
||||
override createTree(options?: BSTOptions<K, V, R>): TREE {
|
||||
return new BST<K, V, R, MK, MV, MR, NODE, TREE>([], {
|
||||
override createTree(options?: BSTOptions<K, V, R>) {
|
||||
return new BST<K, V, R, MK, MV, MR>([], {
|
||||
iterationType: this.iterationType,
|
||||
isMapMode: this._isMapMode,
|
||||
specifyComparable: this._specifyComparable,
|
||||
toEntryFn: this._toEntryFn,
|
||||
isReverse: this._isReverse,
|
||||
...options
|
||||
}) as TREE;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function overrides a method and converts a key, value pair or entry or raw element to a node.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - A variable that can be of
|
||||
* type R or BTNRep<K, V, NODE>. It represents either a key, a node, an entry, or a raw
|
||||
* element.
|
||||
* @param {V} [value] - The `value` parameter is an optional value of type `V`. It represents the
|
||||
* value associated with a key in a key-value pair.
|
||||
* @returns either a NODE object or undefined.
|
||||
*/
|
||||
protected override _keyValueNodeEntryRawToNodeAndValue(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R,
|
||||
value?: V
|
||||
): [OptNode<NODE>, V | undefined] {
|
||||
const [node, entryValue] = super._keyValueNodeEntryRawToNodeAndValue(keyNodeEntryOrRaw, value);
|
||||
if (node === null) return [undefined, undefined];
|
||||
return [node, value ?? entryValue];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -270,7 +245,7 @@ export class BST<
|
|||
*
|
||||
* The function ensures the existence of a node in a data structure and returns it, or undefined if
|
||||
* it doesn't exist.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can accept a value of type `R`, which represents the key, node,
|
||||
* entry, or raw element that needs to be ensured in the tree.
|
||||
* @param {IterationType} [iterationType=ITERATIVE] - The `iterationType` parameter is an optional
|
||||
|
@ -280,20 +255,20 @@ export class BST<
|
|||
* not be ensured.
|
||||
*/
|
||||
override ensureNode(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R,
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, BSTNode<K, V>> | R,
|
||||
iterationType: IterationType = this.iterationType
|
||||
): OptNode<NODE> {
|
||||
): OptNode<BSTNode<K, V>> {
|
||||
return super.ensureNode(keyNodeEntryOrRaw, iterationType) ?? undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function checks if the input is an instance of the BSTNode class.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, BSTNode<K, V>>`.
|
||||
* @returns a boolean value indicating whether the input parameter `keyNodeEntryOrRaw` is
|
||||
* an instance of the `BSTNode` class.
|
||||
*/
|
||||
override isNode(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R): keyNodeEntryOrRaw is NODE {
|
||||
override isNode(keyNodeEntryOrRaw: BTNRep<K, V, BSTNode<K, V>> | R): keyNodeEntryOrRaw is BSTNode<K, V> {
|
||||
return keyNodeEntryOrRaw instanceof BSTNode;
|
||||
}
|
||||
|
||||
|
@ -314,13 +289,13 @@ export class BST<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `add` function in TypeScript adds a new node to a binary search tree based on the key value.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can accept a value of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can accept a value of type `R` or `BTNRep<K, V, BSTNode<K, V>>`.
|
||||
* @param {V} [value] - The `value` parameter is an optional value that can be associated with the
|
||||
* key in the binary search tree. If provided, it will be stored in the node along with the key.
|
||||
* @returns a boolean value.
|
||||
*/
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R, value?: V): boolean {
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, BSTNode<K, V>> | R, value?: V): boolean {
|
||||
const [newNode, newValue] = this._keyValueNodeEntryRawToNodeAndValue(keyNodeEntryOrRaw, value);
|
||||
if (newNode === undefined) return false;
|
||||
|
||||
|
@ -381,7 +356,7 @@ export class BST<
|
|||
* successfully inserted into the data structure.
|
||||
*/
|
||||
override addMany(
|
||||
keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, NODE>>,
|
||||
keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, BSTNode<K, V>>>,
|
||||
values?: Iterable<V | undefined>,
|
||||
isBalanceAdd = true,
|
||||
iterationType: IterationType = this.iterationType
|
||||
|
@ -403,7 +378,7 @@ export class BST<
|
|||
}
|
||||
|
||||
const realBTNExemplars: {
|
||||
key: R | BTNRep<K, V, NODE>;
|
||||
key: R | BTNRep<K, V, BSTNode<K, V>>;
|
||||
value: V | undefined;
|
||||
orgIndex: number;
|
||||
}[] = [];
|
||||
|
@ -414,7 +389,7 @@ export class BST<
|
|||
i++;
|
||||
}
|
||||
|
||||
let sorted: { key: R | BTNRep<K, V, NODE>; value: V | undefined; orgIndex: number }[] = [];
|
||||
let sorted: { key: R | BTNRep<K, V, BSTNode<K, V>>; value: V | undefined; orgIndex: number }[] = [];
|
||||
|
||||
sorted = realBTNExemplars.sort(({ key: a }, { key: b }) => {
|
||||
let keyA: K | undefined | null, keyB: K | undefined | null;
|
||||
|
@ -440,7 +415,7 @@ export class BST<
|
|||
return 0;
|
||||
});
|
||||
|
||||
const _dfs = (arr: { key: R | BTNRep<K, V, NODE>; value: V | undefined; orgIndex: number }[]) => {
|
||||
const _dfs = (arr: { key: R | BTNRep<K, V, BSTNode<K, V>>; value: V | undefined; orgIndex: number }[]) => {
|
||||
if (arr.length === 0) return;
|
||||
|
||||
const mid = Math.floor((arr.length - 1) / 2);
|
||||
|
@ -483,7 +458,7 @@ export class BST<
|
|||
*
|
||||
* The function `search` in TypeScript overrides the search behavior in a binary tree structure based
|
||||
* on specified criteria.
|
||||
* @param {BTNRep<K, V, NODE> | R | NodePredicate<NODE>} keyNodeEntryRawOrPredicate - The
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R | NodePredicate<BSTNode<K, V>>} keyNodeEntryRawOrPredicate - The
|
||||
* `keyNodeEntryRawOrPredicate` parameter in the `override search` method can accept one of the
|
||||
* following types:
|
||||
* @param [onlyOne=false] - The `onlyOne` parameter is a boolean flag that determines whether the
|
||||
|
@ -491,9 +466,9 @@ export class BST<
|
|||
* search will return as soon as a matching node is found. If `onlyOne` is set to `false`, the
|
||||
* @param {C} callback - The `callback` parameter in the `override search` function is a function
|
||||
* that will be called on each node that matches the search criteria. It is of type `C`, which
|
||||
* extends `NodeCallback<NODE>`. The callback function should accept a node of type `NODE` as its
|
||||
* extends `NodeCallback<BSTNode<K, V>>`. The callback function should accept a node of type `BSTNode<K, V>` as its
|
||||
* argument and
|
||||
* @param {BTNRep<K, V, NODE> | R} startNode - The `startNode` parameter in the `override search`
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} startNode - The `startNode` parameter in the `override search`
|
||||
* method represents the node from which the search operation will begin. It is the starting point
|
||||
* for searching within the tree data structure. The method ensures that the `startNode` is a valid
|
||||
* node before proceeding with the search operation. If the `
|
||||
|
@ -505,18 +480,18 @@ export class BST<
|
|||
* structure based on the provided key, predicate, and other options. The search results are
|
||||
* collected in an array and returned as the output of the method.
|
||||
*/
|
||||
override search<C extends NodeCallback<NODE>>(
|
||||
keyNodeEntryRawOrPredicate: BTNRep<K, V, NODE> | R | NodePredicate<NODE> | Range<K>,
|
||||
override search<C extends NodeCallback<BSTNode<K, V>>>(
|
||||
keyNodeEntryRawOrPredicate: BTNRep<K, V, BSTNode<K, V>> | R | NodePredicate<BSTNode<K, V>> | Range<K>,
|
||||
onlyOne = false,
|
||||
callback: C = this._DEFAULT_NODE_CALLBACK as C,
|
||||
startNode: BTNRep<K, V, NODE> | R = this._root,
|
||||
startNode: BTNRep<K, V, BSTNode<K, V>> | R = this._root,
|
||||
iterationType: IterationType = this.iterationType
|
||||
): ReturnType<C>[] {
|
||||
if (keyNodeEntryRawOrPredicate === undefined) return [];
|
||||
if (keyNodeEntryRawOrPredicate === null) return [];
|
||||
startNode = this.ensureNode(startNode);
|
||||
if (!startNode) return [];
|
||||
let predicate: NodePredicate<NODE>;
|
||||
let predicate: NodePredicate<BSTNode<K, V>>;
|
||||
|
||||
const isRange = this.isRange(keyNodeEntryRawOrPredicate);
|
||||
// Set predicate based on parameter type
|
||||
|
@ -525,7 +500,7 @@ export class BST<
|
|||
} else {
|
||||
predicate = this._ensurePredicate(keyNodeEntryRawOrPredicate);
|
||||
}
|
||||
const isToLeftByRange = (cur: NODE) => {
|
||||
const isToLeftByRange = (cur: BSTNode<K, V>) => {
|
||||
if (isRange) {
|
||||
const range = keyNodeEntryRawOrPredicate;
|
||||
const leftS = this.isReverse ? range.high : range.low;
|
||||
|
@ -535,7 +510,7 @@ export class BST<
|
|||
return false;
|
||||
};
|
||||
|
||||
const isToRightByRange = (cur: NODE) => {
|
||||
const isToRightByRange = (cur: BSTNode<K, V>) => {
|
||||
if (isRange) {
|
||||
const range = keyNodeEntryRawOrPredicate;
|
||||
const rightS = this.isReverse ? range.low : range.high;
|
||||
|
@ -547,7 +522,7 @@ export class BST<
|
|||
};
|
||||
const ans: ReturnType<C>[] = [];
|
||||
if (iterationType === 'RECURSIVE') {
|
||||
const dfs = (cur: NODE) => {
|
||||
const dfs = (cur: BSTNode<K, V>) => {
|
||||
if (predicate(cur)) {
|
||||
ans.push(callback(cur));
|
||||
if (onlyOne) return;
|
||||
|
@ -627,9 +602,9 @@ export class BST<
|
|||
* either a `Range` object or an array of two elements representing the range boundaries.
|
||||
* @param {C} callback - The `callback` parameter in the `rangeSearch` function is a callback
|
||||
* function that is used to process each node that is found within the specified range during the
|
||||
* search operation. It is of type `NodeCallback<NODE>`, where `NODE` is the type of nodes in the
|
||||
* search operation. It is of type `NodeCallback<BSTNode<K, V>>`, where `BSTNode<K, V>` is the type of nodes in the
|
||||
* data structure.
|
||||
* @param {BTNRep<K, V, NODE> | R} startNode - The `startNode` parameter in the `rangeSearch`
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} startNode - The `startNode` parameter in the `rangeSearch`
|
||||
* function represents the node from which the search for nodes within the specified range will
|
||||
* begin. It is the starting point for the range search operation.
|
||||
* @param {IterationType} iterationType - The `iterationType` parameter in the `rangeSearch` function
|
||||
|
@ -639,10 +614,10 @@ export class BST<
|
|||
* @returns The `rangeSearch` function is returning the result of calling the `search` method with
|
||||
* the specified parameters.
|
||||
*/
|
||||
rangeSearch<C extends NodeCallback<NODE>>(
|
||||
rangeSearch<C extends NodeCallback<BSTNode<K, V>>>(
|
||||
range: Range<K> | [K, K],
|
||||
callback: C = this._DEFAULT_NODE_CALLBACK as C,
|
||||
startNode: BTNRep<K, V, NODE> | R = this._root,
|
||||
startNode: BTNRep<K, V, BSTNode<K, V>> | R = this._root,
|
||||
iterationType: IterationType = this.iterationType
|
||||
) {
|
||||
const searchRange: Range<K> = range instanceof Range ? range : new Range(range[0], range[1]);
|
||||
|
@ -654,9 +629,9 @@ export class BST<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* This function retrieves a node based on a given keyNodeEntryRawOrPredicate within a binary search tree structure.
|
||||
* @param {BTNRep<K, V, NODE> | R | NodePredicate<NODE>} keyNodeEntryRawOrPredicate - The `keyNodeEntryRawOrPredicate`
|
||||
* parameter can be of type `BTNRep<K, V, NODE>`, `R`, or `NodePredicate<NODE>`.
|
||||
* @param {R | BSTNOptKeyOrNode<K, NODE>} startNode - The `startNode` parameter in the `getNode` method
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R | NodePredicate<BSTNode<K, V>>} keyNodeEntryRawOrPredicate - The `keyNodeEntryRawOrPredicate`
|
||||
* parameter can be of type `BTNRep<K, V, BSTNode<K, V>>`, `R`, or `NodePredicate<BSTNode<K, V>>`.
|
||||
* @param {R | BSTNOptKeyOrNode<K, BSTNode<K, V>>} startNode - The `startNode` parameter in the `getNode` method
|
||||
* is used to specify the starting point for searching nodes in the binary search tree. If no
|
||||
* specific starting point is provided, the default value is set to `this._root`, which is the root
|
||||
* node of the binary search tree.
|
||||
|
@ -664,16 +639,16 @@ export class BST<
|
|||
* parameter that specifies the type of iteration to be used. It has a default value of
|
||||
* `this.iterationType`, which means it will use the iteration type defined in the class instance if
|
||||
* no value is provided when calling the method.
|
||||
* @returns The `getNode` method is returning an optional binary search tree node (`OptNode<NODE>`).
|
||||
* @returns The `getNode` method is returning an optional binary search tree node (`OptNode<BSTNode<K, V>>`).
|
||||
* It is using the `getNodes` method to find the node based on the provided keyNodeEntryRawOrPredicate, beginning at
|
||||
* the specified root node (`startNode`) and using the specified iteration type. The method then
|
||||
* returns the first node found or `undefined` if no node is found.
|
||||
*/
|
||||
override getNode(
|
||||
keyNodeEntryRawOrPredicate: BTNRep<K, V, NODE> | R | NodePredicate<NODE>,
|
||||
startNode: R | BSTNOptKeyOrNode<K, NODE> = this._root,
|
||||
keyNodeEntryRawOrPredicate: BTNRep<K, V, BSTNode<K, V>> | R | NodePredicate<BSTNode<K, V>>,
|
||||
startNode: R | BSTNOptKeyOrNode<K, BSTNode<K, V>> = this._root,
|
||||
iterationType: IterationType = this.iterationType
|
||||
): OptNode<NODE> {
|
||||
): OptNode<BSTNode<K, V>> {
|
||||
return this.getNodes(keyNodeEntryRawOrPredicate, true, startNode, iterationType)[0] ?? undefined;
|
||||
}
|
||||
|
||||
|
@ -689,7 +664,7 @@ export class BST<
|
|||
* @param {DFSOrderPattern} [pattern=IN] - The "pattern" parameter in the code snippet refers to the
|
||||
* order in which the Depth-First Search (DFS) algorithm visits the nodes in a tree or graph. It can
|
||||
* take one of the following values:
|
||||
* @param {BTNRep<K, V, NODE> | R} startNode - The `startNode` parameter is the starting
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} startNode - The `startNode` parameter is the starting
|
||||
* point for the depth-first search traversal. It can be either a root node, a key-value pair, or a
|
||||
* node entry. If not specified, the default value is the root of the tree.
|
||||
* @param {IterationType} [iterationType=ITERATIVE] - The `iterationType` parameter specifies the
|
||||
|
@ -697,10 +672,10 @@ export class BST<
|
|||
* following values:
|
||||
* @returns The method is returning an array of the return type of the callback function.
|
||||
*/
|
||||
override dfs<C extends NodeCallback<NODE>>(
|
||||
override dfs<C extends NodeCallback<BSTNode<K, V>>>(
|
||||
callback: C = this._DEFAULT_NODE_CALLBACK as C,
|
||||
pattern: DFSOrderPattern = 'IN',
|
||||
startNode: BTNRep<K, V, NODE> | R = this._root,
|
||||
startNode: BTNRep<K, V, BSTNode<K, V>> | R = this._root,
|
||||
iterationType: IterationType = this.iterationType
|
||||
): ReturnType<C>[] {
|
||||
return super.dfs(callback, pattern, startNode, iterationType);
|
||||
|
@ -715,7 +690,7 @@ export class BST<
|
|||
* @param {C} callback - The `callback` parameter is a function that will be called for each node
|
||||
* visited during the breadth-first search. It should take a single argument, which is the current
|
||||
* node being visited, and it can return a value of any type.
|
||||
* @param {BTNRep<K, V, NODE> | R} startNode - The `startNode` parameter is the starting
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} startNode - The `startNode` parameter is the starting
|
||||
* point for the breadth-first search. It can be either a root node, a key-value pair, or an entry
|
||||
* object. If no value is provided, the default value is the root of the tree.
|
||||
* @param {IterationType} iterationType - The `iterationType` parameter is used to specify the type
|
||||
|
@ -723,9 +698,9 @@ export class BST<
|
|||
* the following values:
|
||||
* @returns an array of the return type of the callback function.
|
||||
*/
|
||||
override bfs<C extends NodeCallback<NODE>>(
|
||||
override bfs<C extends NodeCallback<BSTNode<K, V>>>(
|
||||
callback: C = this._DEFAULT_NODE_CALLBACK as C,
|
||||
startNode: BTNRep<K, V, NODE> | R = this._root,
|
||||
startNode: BTNRep<K, V, BSTNode<K, V>> | R = this._root,
|
||||
iterationType: IterationType = this.iterationType
|
||||
): ReturnType<C>[] {
|
||||
return super.bfs(callback, startNode, iterationType, false);
|
||||
|
@ -738,9 +713,9 @@ export class BST<
|
|||
* The function overrides the listLevels method from the superclass and returns an array of arrays
|
||||
* containing the results of the callback function applied to each level of the tree.
|
||||
* @param {C} callback - The `callback` parameter is a generic type `C` that extends
|
||||
* `NodeCallback<NODE>`. It represents a callback function that will be called for each node in the
|
||||
* `NodeCallback<BSTNode<K, V>>`. It represents a callback function that will be called for each node in the
|
||||
* tree during the iteration process.
|
||||
* @param {BTNRep<K, V, NODE> | R} startNode - The `startNode` parameter is the starting
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} startNode - The `startNode` parameter is the starting
|
||||
* point for listing the levels of the binary tree. It can be either a root node of the tree, a
|
||||
* key-value pair representing a node in the tree, or a key representing a node in the tree. If no
|
||||
* value is provided, the root of
|
||||
|
@ -749,9 +724,9 @@ export class BST<
|
|||
* @returns The method is returning a two-dimensional array of the return type of the callback
|
||||
* function.
|
||||
*/
|
||||
override listLevels<C extends NodeCallback<NODE>>(
|
||||
override listLevels<C extends NodeCallback<BSTNode<K, V>>>(
|
||||
callback: C = this._DEFAULT_NODE_CALLBACK as C,
|
||||
startNode: BTNRep<K, V, NODE> | R = this._root,
|
||||
startNode: BTNRep<K, V, BSTNode<K, V>> | R = this._root,
|
||||
iterationType: IterationType = this.iterationType
|
||||
): ReturnType<C>[][] {
|
||||
return super.listLevels(callback, startNode, iterationType, false);
|
||||
|
@ -769,7 +744,7 @@ export class BST<
|
|||
* @param {CP} lesserOrGreater - The `lesserOrGreater` parameter is used to determine whether to
|
||||
* traverse nodes that are lesser, greater, or both than the `targetNode`. It accepts the values -1,
|
||||
* 0, or 1, where:
|
||||
* @param {BTNRep<K, V, NODE> | R} targetNode - The `targetNode` parameter is the node in
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} targetNode - The `targetNode` parameter is the node in
|
||||
* the binary tree that you want to start traversing from. It can be specified either by providing
|
||||
* the key of the node, the node itself, or an entry containing the key and value of the node. If no
|
||||
* `targetNode` is provided,
|
||||
|
@ -778,21 +753,21 @@ export class BST<
|
|||
* @returns The function `lesserOrGreaterTraverse` returns an array of values of type
|
||||
* `ReturnType<C>`, which is the return type of the callback function passed as an argument.
|
||||
*/
|
||||
lesserOrGreaterTraverse<C extends NodeCallback<NODE>>(
|
||||
lesserOrGreaterTraverse<C extends NodeCallback<BSTNode<K, V>>>(
|
||||
callback: C = this._DEFAULT_NODE_CALLBACK as C,
|
||||
lesserOrGreater: CP = -1,
|
||||
targetNode: BTNRep<K, V, NODE> | R = this._root,
|
||||
targetNode: BTNRep<K, V, BSTNode<K, V>> | R = this._root,
|
||||
iterationType: IterationType = this.iterationType
|
||||
): ReturnType<C>[] {
|
||||
const targetNodeEnsured = this.ensureNode(targetNode);
|
||||
const ans: ReturnType<NodeCallback<NODE>>[] = [];
|
||||
const ans: ReturnType<NodeCallback<BSTNode<K, V>>>[] = [];
|
||||
if (!this._root) return ans;
|
||||
if (!targetNodeEnsured) return ans;
|
||||
|
||||
const targetKey = targetNodeEnsured.key;
|
||||
|
||||
if (iterationType === 'RECURSIVE') {
|
||||
const dfs = (cur: NODE) => {
|
||||
const dfs = (cur: BSTNode<K, V>) => {
|
||||
const compared = this._compare(cur.key, targetKey);
|
||||
if (Math.sign(compared) === lesserOrGreater) ans.push(callback(cur));
|
||||
// TODO here can be optimized to O(log n)
|
||||
|
@ -803,7 +778,7 @@ export class BST<
|
|||
dfs(this._root);
|
||||
return ans;
|
||||
} else {
|
||||
const queue = new Queue<NODE>([this._root]);
|
||||
const queue = new Queue<BSTNode<K, V>>([this._root]);
|
||||
while (queue.size > 0) {
|
||||
const cur = queue.shift();
|
||||
if (this.isRealNode(cur)) {
|
||||
|
@ -887,7 +862,7 @@ export class BST<
|
|||
let balanced = true;
|
||||
|
||||
if (iterationType === 'RECURSIVE') {
|
||||
const _height = (cur: OptNodeOrNull<NODE>): number => {
|
||||
const _height = (cur: OptNodeOrNull<BSTNode<K, V>>): number => {
|
||||
if (!cur) return 0;
|
||||
const leftHeight = _height(cur.left),
|
||||
rightHeight = _height(cur.right);
|
||||
|
@ -896,10 +871,10 @@ export class BST<
|
|||
};
|
||||
_height(this._root);
|
||||
} else {
|
||||
const stack: NODE[] = [];
|
||||
let node: OptNode<NODE> = this._root,
|
||||
last: OptNode<NODE> = undefined;
|
||||
const depths: Map<NODE, number> = new Map();
|
||||
const stack: BSTNode<K, V>[] = [];
|
||||
let node: OptNode<BSTNode<K, V>> = this._root,
|
||||
last: OptNode<BSTNode<K, V>> = undefined;
|
||||
const depths: Map<BSTNode<K, V>, number> = new Map();
|
||||
|
||||
while (stack.length > 0 || node) {
|
||||
if (node) {
|
||||
|
@ -925,61 +900,6 @@ export class BST<
|
|||
return balanced;
|
||||
}
|
||||
|
||||
protected _comparator: Comparator<K> = (a: K, b: K): number => {
|
||||
if (isComparable(a) && isComparable(b)) {
|
||||
if (a > b) return 1;
|
||||
if (a < b) return -1;
|
||||
return 0;
|
||||
}
|
||||
if (this._specifyComparable) {
|
||||
if (this._specifyComparable(a) > this._specifyComparable(b)) return 1;
|
||||
if (this._specifyComparable(a) < this._specifyComparable(b)) return -1;
|
||||
return 0;
|
||||
}
|
||||
if (typeof a === 'object' || typeof b === 'object') {
|
||||
throw TypeError(
|
||||
`When comparing object types, a custom specifyComparable must be defined in the constructor's options parameter.`
|
||||
);
|
||||
}
|
||||
|
||||
return 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* The function returns the value of the _comparator property.
|
||||
* @returns The `_comparator` property is being returned.
|
||||
*/
|
||||
get comparator() {
|
||||
return this._comparator;
|
||||
}
|
||||
|
||||
protected _specifyComparable?: (key: K) => Comparable;
|
||||
|
||||
/**
|
||||
* This function returns the value of the `_specifyComparable` property.
|
||||
* @returns The method `specifyComparable()` is being returned, which is a getter method for the
|
||||
* `_specifyComparable` property.
|
||||
*/
|
||||
get specifyComparable() {
|
||||
return this._specifyComparable;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function sets the root of a tree-like structure and updates the parent property of the new
|
||||
* root.
|
||||
* @param {OptNode<NODE>} v - v is a parameter of type NODE or undefined.
|
||||
*/
|
||||
protected override _setRoot(v: OptNode<NODE>) {
|
||||
if (v) {
|
||||
v.parent = undefined;
|
||||
}
|
||||
this._root = v;
|
||||
}
|
||||
|
||||
protected _compare(a: K, b: K) {
|
||||
return this._isReverse ? -this._comparator(a, b) : this._comparator(a, b);
|
||||
}
|
||||
|
||||
override map(
|
||||
callback: EntryCallback<K, V | undefined, [MK, MV]>,
|
||||
options?: BSTOptions<MK, MV, MR>,
|
||||
|
@ -992,4 +912,44 @@ export class BST<
|
|||
}
|
||||
return newTree;
|
||||
}
|
||||
|
||||
override clone() {
|
||||
const cloned = this.createTree();
|
||||
this._clone(cloned);
|
||||
return cloned;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function overrides a method and converts a key, value pair or entry or raw element to a node.
|
||||
* @param {BTNRep<K, V, BSTNode<K, V>> | R} keyNodeEntryOrRaw - A variable that can be of
|
||||
* type R or BTNRep<K, V, BSTNode<K, V>>. It represents either a key, a node, an entry, or a raw
|
||||
* element.
|
||||
* @param {V} [value] - The `value` parameter is an optional value of type `V`. It represents the
|
||||
* value associated with a key in a key-value pair.
|
||||
* @returns either a BSTNode<K, V> object or undefined.
|
||||
*/
|
||||
protected override _keyValueNodeEntryRawToNodeAndValue(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, BSTNode<K, V>> | R,
|
||||
value?: V
|
||||
): [OptNode<BSTNode<K, V>>, V | undefined] {
|
||||
const [node, entryValue] = super._keyValueNodeEntryRawToNodeAndValue(keyNodeEntryOrRaw, value);
|
||||
if (node === null) return [undefined, undefined];
|
||||
return [node, value ?? entryValue];
|
||||
}
|
||||
|
||||
/**
|
||||
* The function sets the root of a tree-like structure and updates the parent property of the new
|
||||
* root.
|
||||
* @param {OptNode<BSTNode<K, V>>} v - v is a parameter of type BSTNode<K, V> or undefined.
|
||||
*/
|
||||
protected override _setRoot(v: OptNode<BSTNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = undefined;
|
||||
}
|
||||
this._root = v;
|
||||
}
|
||||
|
||||
protected _compare(a: K, b: K) {
|
||||
return this._isReverse ? -this._comparator(a, b) : this._comparator(a, b);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,19 +4,14 @@ import type {
|
|||
CRUD,
|
||||
EntryCallback,
|
||||
OptNode,
|
||||
OptNodeOrNull,
|
||||
RBTNColor,
|
||||
RedBlackTreeOptions,
|
||||
RedBlackTreeNested,
|
||||
RedBlackTreeNodeNested
|
||||
RedBlackTreeOptions
|
||||
} from '../../types';
|
||||
import { BST, BSTNode } from './bst';
|
||||
import { IBinaryTree } from '../../interfaces';
|
||||
|
||||
export class RedBlackTreeNode<
|
||||
K = any,
|
||||
V = any,
|
||||
NODE extends RedBlackTreeNode<K, V, NODE> = RedBlackTreeNodeNested<K, V>
|
||||
> extends BSTNode<K, V, NODE> {
|
||||
export class RedBlackTreeNode<K = any, V = any> extends BSTNode<K, V> {
|
||||
/**
|
||||
* The constructor function initializes a Red-Black Tree Node with a key, an optional value, and a
|
||||
* color.
|
||||
|
@ -32,6 +27,34 @@ export class RedBlackTreeNode<
|
|||
super(key, value);
|
||||
this._color = color;
|
||||
}
|
||||
|
||||
override parent?: RedBlackTreeNode<K, V> = undefined;
|
||||
|
||||
override _left?: OptNodeOrNull<RedBlackTreeNode<K, V>> = undefined;
|
||||
|
||||
override get left(): OptNodeOrNull<RedBlackTreeNode<K, V>> {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
override set left(v: OptNodeOrNull<RedBlackTreeNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this;
|
||||
}
|
||||
this._left = v;
|
||||
}
|
||||
|
||||
override _right?: OptNodeOrNull<RedBlackTreeNode<K, V>> = undefined;
|
||||
|
||||
override get right(): OptNodeOrNull<RedBlackTreeNode<K, V>> {
|
||||
return this._right;
|
||||
}
|
||||
|
||||
override set right(v: OptNodeOrNull<RedBlackTreeNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this;
|
||||
}
|
||||
this._right = v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -87,27 +110,9 @@ export class RedBlackTreeNode<
|
|||
* );
|
||||
* console.log(stocksInRange); // ['GOOGL', 'MSFT', 'META']
|
||||
*/
|
||||
export class RedBlackTree<
|
||||
K = any,
|
||||
V = any,
|
||||
R = object,
|
||||
MK = any,
|
||||
MV = any,
|
||||
MR = object,
|
||||
NODE extends RedBlackTreeNode<K, V, NODE> = RedBlackTreeNode<K, V, RedBlackTreeNodeNested<K, V>>,
|
||||
TREE extends RedBlackTree<K, V, R, MK, MV, MR, NODE, TREE> = RedBlackTree<
|
||||
K,
|
||||
V,
|
||||
R,
|
||||
MK,
|
||||
MV,
|
||||
MR,
|
||||
NODE,
|
||||
RedBlackTreeNested<K, V, R, MK, MV, MR, NODE>
|
||||
>
|
||||
>
|
||||
extends BST<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
export class RedBlackTree<K = any, V = any, R = object, MK = any, MV = any, MR = object>
|
||||
extends BST<K, V, R, MK, MV, MR>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR>
|
||||
{
|
||||
/**
|
||||
* This is the constructor function for a Red-Black Tree data structure in TypeScript.
|
||||
|
@ -119,7 +124,10 @@ export class RedBlackTree<
|
|||
* configuring the behavior of the Red-Black Tree. The specific properties and their meanings would
|
||||
* depend on the implementation
|
||||
*/
|
||||
constructor(keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, NODE>> = [], options?: RedBlackTreeOptions<K, V, R>) {
|
||||
constructor(
|
||||
keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, RedBlackTreeNode<K, V>>> = [],
|
||||
options?: RedBlackTreeOptions<K, V, R>
|
||||
) {
|
||||
super([], options);
|
||||
|
||||
this._root = this.NIL;
|
||||
|
@ -129,13 +137,13 @@ export class RedBlackTree<
|
|||
}
|
||||
}
|
||||
|
||||
protected override _root: NODE | undefined;
|
||||
protected override _root: RedBlackTreeNode<K, V> | undefined;
|
||||
|
||||
/**
|
||||
* The function returns the root node of a tree or undefined if there is no root.
|
||||
* @returns The root node of the tree structure, or undefined if there is no root node.
|
||||
*/
|
||||
override get root(): NODE | undefined {
|
||||
override get root(): RedBlackTreeNode<K, V> | undefined {
|
||||
return this._root;
|
||||
}
|
||||
|
||||
|
@ -153,8 +161,8 @@ export class RedBlackTree<
|
|||
* @returns A new instance of a RedBlackTreeNode with the specified key, value, and color is being
|
||||
* returned.
|
||||
*/
|
||||
override createNode(key: K, value?: V, color: RBTNColor = 'BLACK'): NODE {
|
||||
return new RedBlackTreeNode<K, V, NODE>(key, this._isMapMode ? undefined : value, color) as NODE;
|
||||
override createNode(key: K, value?: V, color: RBTNColor = 'BLACK'): RedBlackTreeNode<K, V> {
|
||||
return new RedBlackTreeNode<K, V>(key, this._isMapMode ? undefined : value, color) as RedBlackTreeNode<K, V>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -163,14 +171,14 @@ export class RedBlackTree<
|
|||
* configuration options for creating the Red-Black Tree. It has the following properties:
|
||||
* @returns a new instance of a RedBlackTree object.
|
||||
*/
|
||||
override createTree(options?: RedBlackTreeOptions<K, V, R>): TREE {
|
||||
return new RedBlackTree<K, V, R, MK, MV, MR, NODE, TREE>([], {
|
||||
override createTree(options?: RedBlackTreeOptions<K, V, R>) {
|
||||
return new RedBlackTree<K, V, R, MK, MV, MR>([], {
|
||||
iterationType: this.iterationType,
|
||||
isMapMode: this._isMapMode,
|
||||
specifyComparable: this._specifyComparable,
|
||||
toEntryFn: this._toEntryFn,
|
||||
...options
|
||||
}) as TREE;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -178,12 +186,14 @@ export class RedBlackTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function checks if the input is an instance of the RedBlackTreeNode class.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, RedBlackTreeNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, RedBlackTreeNode<K, V>>`.
|
||||
* @returns a boolean value indicating whether the input parameter `keyNodeEntryOrRaw` is
|
||||
* an instance of the `RedBlackTreeNode` class.
|
||||
*/
|
||||
override isNode(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R): keyNodeEntryOrRaw is NODE {
|
||||
override isNode(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, RedBlackTreeNode<K, V>> | R
|
||||
): keyNodeEntryOrRaw is RedBlackTreeNode<K, V> {
|
||||
return keyNodeEntryOrRaw instanceof RedBlackTreeNode;
|
||||
}
|
||||
|
||||
|
@ -205,8 +215,8 @@ export class RedBlackTree<
|
|||
*
|
||||
* The function adds a new node to a binary search tree and returns true if the node was successfully
|
||||
* added.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can accept a value of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, RedBlackTreeNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can accept a value of type `R` or `BTNRep<K, V, RedBlackTreeNode<K, V>>`.
|
||||
* @param {V} [value] - The `value` parameter is an optional value that you want to associate with
|
||||
* the key in the data structure. It represents the value that you want to add or update in the data
|
||||
* structure.
|
||||
|
@ -214,7 +224,7 @@ export class RedBlackTree<
|
|||
* the method returns true. If the node already exists and its value is updated, the method also
|
||||
* returns true. If the node cannot be added or updated, the method returns false.
|
||||
*/
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R, value?: V): boolean {
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, RedBlackTreeNode<K, V>> | R, value?: V): boolean {
|
||||
const [newNode, newValue] = this._keyValueNodeEntryRawToNodeAndValue(keyNodeEntryOrRaw, value);
|
||||
if (!this.isRealNode(newNode)) return false;
|
||||
|
||||
|
@ -244,19 +254,21 @@ export class RedBlackTree<
|
|||
*
|
||||
* The function overrides the delete method in a binary tree data structure to remove a node based on
|
||||
* a given predicate and maintain the binary search tree properties.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The `keyNodeEntryOrRaw`
|
||||
* @param {BTNRep<K, V, RedBlackTreeNode<K, V>> | R} keyNodeEntryOrRaw - The `keyNodeEntryOrRaw`
|
||||
* parameter in the `override delete` method is used to specify the condition or key based on which a
|
||||
* node should be deleted from the binary tree. It can be a key, a node, an entry, or a predicate
|
||||
* function that determines which node(s) should be deleted.
|
||||
* @returns The `override delete` method is returning an array of `BinaryTreeDeleteResult<NODE>`
|
||||
* @returns The `override delete` method is returning an array of `BinaryTreeDeleteResult<RedBlackTreeNode<K, V>>`
|
||||
* objects. Each object in the array contains information about the deleted node and whether
|
||||
* balancing is needed.
|
||||
*/
|
||||
override delete(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R): BinaryTreeDeleteResult<NODE>[] {
|
||||
override delete(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, RedBlackTreeNode<K, V>> | R
|
||||
): BinaryTreeDeleteResult<RedBlackTreeNode<K, V>>[] {
|
||||
if (keyNodeEntryOrRaw === null) return [];
|
||||
|
||||
const results: BinaryTreeDeleteResult<NODE>[] = [];
|
||||
let nodeToDelete: OptNode<NODE>;
|
||||
const results: BinaryTreeDeleteResult<RedBlackTreeNode<K, V>>[] = [];
|
||||
let nodeToDelete: OptNode<RedBlackTreeNode<K, V>>;
|
||||
if (this._isPredicate(keyNodeEntryOrRaw)) nodeToDelete = this.getNode(keyNodeEntryOrRaw);
|
||||
else nodeToDelete = this.isRealNode(keyNodeEntryOrRaw) ? keyNodeEntryOrRaw : this.getNode(keyNodeEntryOrRaw);
|
||||
|
||||
|
@ -265,7 +277,7 @@ export class RedBlackTree<
|
|||
}
|
||||
|
||||
let originalColor = nodeToDelete.color;
|
||||
let replacementNode: NODE | undefined;
|
||||
let replacementNode: RedBlackTreeNode<K, V> | undefined;
|
||||
|
||||
if (!this.isRealNode(nodeToDelete.left)) {
|
||||
if (nodeToDelete.right !== null) {
|
||||
|
@ -316,15 +328,54 @@ export class RedBlackTree<
|
|||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time Complexity: O(n)
|
||||
* Space Complexity: O(n)
|
||||
*
|
||||
* The `map` function in TypeScript overrides the default behavior to create a new Red-Black Tree by
|
||||
* applying a callback to each entry in the original tree.
|
||||
* @param callback - A function that will be called for each entry in the tree, with parameters
|
||||
* representing the key, value, index, and the tree itself. It should return an entry for the new
|
||||
* tree.
|
||||
* @param [options] - The `options` parameter in the `map` method is of type `RedBlackTreeOptions<MK, MV,
|
||||
* MR>`. This parameter allows you to specify additional options or configurations for the Red-Black
|
||||
* Tree that will be created during the mapping process. These options could include things like
|
||||
* custom comparators
|
||||
* @param {any} [thisArg] - The `thisArg` parameter in the `override map` function is used to specify
|
||||
* the value of `this` when executing the `callback` function. It allows you to set the context
|
||||
* (value of `this`) for the callback function. This can be useful when you want to access properties
|
||||
* or
|
||||
* @returns A new Red-Black Tree is being returned, where each entry has been transformed using the
|
||||
* provided callback function.
|
||||
*/
|
||||
override map(
|
||||
callback: EntryCallback<K, V | undefined, [MK, MV]>,
|
||||
options?: RedBlackTreeOptions<MK, MV, MR>,
|
||||
thisArg?: any
|
||||
): RedBlackTree<MK, MV, MR> {
|
||||
const newTree = new RedBlackTree<MK, MV, MR>([], options);
|
||||
let index = 0;
|
||||
for (const [key, value] of this) {
|
||||
newTree.add(callback.call(thisArg, key, value, index++, this));
|
||||
}
|
||||
return newTree;
|
||||
}
|
||||
|
||||
override clone() {
|
||||
const cloned = this.createTree();
|
||||
this._clone(cloned);
|
||||
return cloned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time Complexity: O(1)
|
||||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function sets the root of a tree-like structure and updates the parent property of the new
|
||||
* root.
|
||||
* @param {NODE | undefined} v - v is a parameter of type NODE or undefined.
|
||||
* @param {RedBlackTreeNode<K, V> | undefined} v - v is a parameter of type RedBlackTreeNode<K, V> or undefined.
|
||||
*/
|
||||
protected override _setRoot(v: NODE | undefined) {
|
||||
protected override _setRoot(v: RedBlackTreeNode<K, V> | undefined) {
|
||||
if (v) {
|
||||
v.parent = undefined;
|
||||
}
|
||||
|
@ -336,14 +387,17 @@ export class RedBlackTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function replaces an old node with a new node while preserving the color of the old node.
|
||||
* @param {NODE} oldNode - The `oldNode` parameter represents the node that needs to be replaced in
|
||||
* @param {RedBlackTreeNode<K, V>} oldNode - The `oldNode` parameter represents the node that needs to be replaced in
|
||||
* the data structure.
|
||||
* @param {NODE} newNode - The `newNode` parameter is of type `NODE`, which represents a node in a
|
||||
* @param {RedBlackTreeNode<K, V>} newNode - The `newNode` parameter is of type `RedBlackTreeNode<K, V>`, which represents a node in a
|
||||
* data structure.
|
||||
* @returns The method is returning the result of calling the `_replaceNode` method from the
|
||||
* superclass, with the `oldNode` and `newNode` parameters.
|
||||
*/
|
||||
protected override _replaceNode(oldNode: NODE, newNode: NODE): NODE {
|
||||
protected override _replaceNode(
|
||||
oldNode: RedBlackTreeNode<K, V>,
|
||||
newNode: RedBlackTreeNode<K, V>
|
||||
): RedBlackTreeNode<K, V> {
|
||||
newNode.color = oldNode.color;
|
||||
|
||||
return super._replaceNode(oldNode, newNode);
|
||||
|
@ -355,15 +409,15 @@ export class RedBlackTree<
|
|||
*
|
||||
* The `_insert` function inserts a node into a binary search tree and performs necessary fix-ups to
|
||||
* maintain the red-black tree properties.
|
||||
* @param {NODE} node - The `node` parameter represents the node that needs to be inserted into the
|
||||
* @param {RedBlackTreeNode<K, V>} node - The `node` parameter represents the node that needs to be inserted into the
|
||||
* binary search tree.
|
||||
* @returns a string value indicating the result of the insertion operation. It can return either
|
||||
* 'UPDATED' if the node with the same key already exists and was updated, or 'CREATED' if a new node
|
||||
* was created and inserted into the tree.
|
||||
*/
|
||||
protected _insert(node: NODE): CRUD {
|
||||
protected _insert(node: RedBlackTreeNode<K, V>): CRUD {
|
||||
let current = this.root;
|
||||
let parent: NODE | undefined = undefined;
|
||||
let parent: RedBlackTreeNode<K, V> | undefined = undefined;
|
||||
|
||||
while (this.isRealNode(current)) {
|
||||
parent = current;
|
||||
|
@ -401,11 +455,11 @@ export class RedBlackTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function `_transplant` is used to replace a node `u` with another node `v` in a binary tree.
|
||||
* @param {NODE} u - The parameter "u" represents a node in a binary tree.
|
||||
* @param {NODE | undefined} v - The parameter `v` is of type `NODE | undefined`, which means it can
|
||||
* either be a `NODE` object or `undefined`.
|
||||
* @param {RedBlackTreeNode<K, V>} u - The parameter "u" represents a node in a binary tree.
|
||||
* @param {RedBlackTreeNode<K, V> | undefined} v - The parameter `v` is of type `RedBlackTreeNode<K, V> | undefined`, which means it can
|
||||
* either be a `RedBlackTreeNode<K, V>` object or `undefined`.
|
||||
*/
|
||||
protected _transplant(u: NODE, v: NODE | undefined): void {
|
||||
protected _transplant(u: RedBlackTreeNode<K, V>, v: RedBlackTreeNode<K, V> | undefined): void {
|
||||
if (!u.parent) {
|
||||
this._setRoot(v);
|
||||
} else if (u === u.parent.left) {
|
||||
|
@ -424,10 +478,10 @@ export class RedBlackTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `_insertFixup` function is used to fix the Red-Black Tree after inserting a new node.
|
||||
* @param {NODE | undefined} z - The parameter `z` represents a node in the Red-Black Tree data
|
||||
* @param {RedBlackTreeNode<K, V> | undefined} z - The parameter `z` represents a node in the Red-Black Tree data
|
||||
* structure. It can either be a valid node or `undefined`.
|
||||
*/
|
||||
protected _insertFixup(z: NODE | undefined): void {
|
||||
protected _insertFixup(z: RedBlackTreeNode<K, V> | undefined): void {
|
||||
// Continue fixing the tree as long as the parent of z is red
|
||||
while (z?.parent?.color === 'RED') {
|
||||
// Check if the parent of z is the left child of its parent
|
||||
|
@ -460,7 +514,7 @@ export class RedBlackTree<
|
|||
} else {
|
||||
// Symmetric case for the right child (left and right exchanged)
|
||||
// Follow the same logic as above with left and right exchanged
|
||||
const y: NODE | undefined = z?.parent?.parent?.left ?? undefined;
|
||||
const y: RedBlackTreeNode<K, V> | undefined = z?.parent?.parent?.left ?? undefined;
|
||||
if (y?.color === 'RED') {
|
||||
z.parent.color = 'BLACK';
|
||||
y.color = 'BLACK';
|
||||
|
@ -491,12 +545,12 @@ export class RedBlackTree<
|
|||
*
|
||||
* The `_deleteFixup` function is used to fix the red-black tree after a node deletion by adjusting
|
||||
* the colors and performing rotations.
|
||||
* @param {NODE | undefined} node - The `node` parameter represents a node in a binary tree. It can
|
||||
* @param {RedBlackTreeNode<K, V> | undefined} node - The `node` parameter represents a node in a binary tree. It can
|
||||
* be either a valid node object or `undefined`.
|
||||
* @returns The function does not return any value. It has a return type of `void`, which means it
|
||||
* does not return anything.
|
||||
*/
|
||||
protected _deleteFixup(node: NODE | undefined): void {
|
||||
protected _deleteFixup(node: RedBlackTreeNode<K, V> | undefined): void {
|
||||
// Early exit condition
|
||||
if (!node || node === this.root || node.color === 'BLACK') {
|
||||
if (node) {
|
||||
|
@ -506,7 +560,7 @@ export class RedBlackTree<
|
|||
}
|
||||
|
||||
while (node && node !== this.root && node.color === 'BLACK') {
|
||||
const parent: NODE | undefined = node.parent;
|
||||
const parent: RedBlackTreeNode<K, V> | undefined = node.parent;
|
||||
|
||||
if (!parent) {
|
||||
break; // Ensure the loop terminates if there's an issue with the tree structure
|
||||
|
@ -573,11 +627,11 @@ export class RedBlackTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `_leftRotate` function performs a left rotation on a given node in a binary tree.
|
||||
* @param {NODE | undefined} x - The parameter `x` is of type `NODE | undefined`. It represents a
|
||||
* @param {RedBlackTreeNode<K, V> | undefined} x - The parameter `x` is of type `RedBlackTreeNode<K, V> | undefined`. It represents a
|
||||
* node in a binary tree or `undefined` if there is no node.
|
||||
* @returns void, which means it does not return any value.
|
||||
*/
|
||||
protected _leftRotate(x: NODE | undefined): void {
|
||||
protected _leftRotate(x: RedBlackTreeNode<K, V> | undefined): void {
|
||||
if (!x || !x.right) {
|
||||
return;
|
||||
}
|
||||
|
@ -608,11 +662,11 @@ export class RedBlackTree<
|
|||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `_rightRotate` function performs a right rotation on a given node in a binary tree.
|
||||
* @param {NODE | undefined} y - The parameter `y` is of type `NODE | undefined`. It represents a
|
||||
* @param {RedBlackTreeNode<K, V> | undefined} y - The parameter `y` is of type `RedBlackTreeNode<K, V> | undefined`. It represents a
|
||||
* node in a binary tree or `undefined` if there is no node.
|
||||
* @returns void, which means it does not return any value.
|
||||
*/
|
||||
protected _rightRotate(y: NODE | undefined): void {
|
||||
protected _rightRotate(y: RedBlackTreeNode<K, V> | undefined): void {
|
||||
if (!y || !y.left) {
|
||||
return;
|
||||
}
|
||||
|
@ -637,37 +691,4 @@ export class RedBlackTree<
|
|||
x.right = y;
|
||||
y.parent = x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time Complexity: O(n)
|
||||
* Space Complexity: O(n)
|
||||
*
|
||||
* The `map` function in TypeScript overrides the default behavior to create a new Red-Black Tree by
|
||||
* applying a callback to each entry in the original tree.
|
||||
* @param callback - A function that will be called for each entry in the tree, with parameters
|
||||
* representing the key, value, index, and the tree itself. It should return an entry for the new
|
||||
* tree.
|
||||
* @param [options] - The `options` parameter in the `map` method is of type `RedBlackTreeOptions<MK, MV,
|
||||
* MR>`. This parameter allows you to specify additional options or configurations for the Red-Black
|
||||
* Tree that will be created during the mapping process. These options could include things like
|
||||
* custom comparators
|
||||
* @param {any} [thisArg] - The `thisArg` parameter in the `override map` function is used to specify
|
||||
* the value of `this` when executing the `callback` function. It allows you to set the context
|
||||
* (value of `this`) for the callback function. This can be useful when you want to access properties
|
||||
* or
|
||||
* @returns A new Red-Black Tree is being returned, where each entry has been transformed using the
|
||||
* provided callback function.
|
||||
*/
|
||||
override map(
|
||||
callback: EntryCallback<K, V | undefined, [MK, MV]>,
|
||||
options?: RedBlackTreeOptions<MK, MV, MR>,
|
||||
thisArg?: any
|
||||
): RedBlackTree<MK, MV, MR> {
|
||||
const newTree = new RedBlackTree<MK, MV, MR>([], options);
|
||||
let index = 0;
|
||||
for (const [key, value] of this) {
|
||||
newTree.add(callback.call(thisArg, key, value, index++, this));
|
||||
}
|
||||
return newTree;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,19 +12,14 @@ import type {
|
|||
EntryCallback,
|
||||
IterationType,
|
||||
OptNode,
|
||||
OptNodeOrNull,
|
||||
RBTNColor,
|
||||
TreeMultiMapNested,
|
||||
TreeMultiMapNodeNested,
|
||||
TreeMultiMapOptions
|
||||
} from '../../types';
|
||||
import { IBinaryTree } from '../../interfaces';
|
||||
import { RedBlackTree, RedBlackTreeNode } from './red-black-tree';
|
||||
|
||||
export class TreeMultiMapNode<
|
||||
K = any,
|
||||
V = any,
|
||||
NODE extends TreeMultiMapNode<K, V, NODE> = TreeMultiMapNodeNested<K, V>
|
||||
> extends RedBlackTreeNode<K, V, NODE> {
|
||||
export class TreeMultiMapNode<K = any, V = any> extends RedBlackTreeNode<K, V> {
|
||||
/**
|
||||
* The constructor function initializes a Red-Black Tree node with a key, value, count, and color.
|
||||
* @param {K} key - The key parameter represents the key of the node in the Red-Black Tree. It is
|
||||
|
@ -41,29 +36,39 @@ export class TreeMultiMapNode<
|
|||
super(key, value, color);
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
override parent?: TreeMultiMapNode<K, V> = undefined;
|
||||
|
||||
override _left?: OptNodeOrNull<TreeMultiMapNode<K, V>> = undefined;
|
||||
|
||||
override get left(): OptNodeOrNull<TreeMultiMapNode<K, V>> {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
override set left(v: OptNodeOrNull<TreeMultiMapNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this;
|
||||
}
|
||||
this._left = v;
|
||||
}
|
||||
|
||||
override _right?: OptNodeOrNull<TreeMultiMapNode<K, V>> = undefined;
|
||||
|
||||
override get right(): OptNodeOrNull<TreeMultiMapNode<K, V>> {
|
||||
return this._right;
|
||||
}
|
||||
|
||||
override set right(v: OptNodeOrNull<TreeMultiMapNode<K, V>>) {
|
||||
if (v) {
|
||||
v.parent = this;
|
||||
}
|
||||
this._right = v;
|
||||
}
|
||||
}
|
||||
|
||||
export class TreeMultiMap<
|
||||
K = any,
|
||||
V = any,
|
||||
R = object,
|
||||
MK = any,
|
||||
MV = any,
|
||||
MR = object,
|
||||
NODE extends TreeMultiMapNode<K, V, NODE> = TreeMultiMapNode<K, V, TreeMultiMapNodeNested<K, V>>,
|
||||
TREE extends TreeMultiMap<K, V, R, MK, MV, MR, NODE, TREE> = TreeMultiMap<
|
||||
K,
|
||||
V,
|
||||
R,
|
||||
MK,
|
||||
MV,
|
||||
MR,
|
||||
NODE,
|
||||
TreeMultiMapNested<K, V, R, MK, MV, MR, NODE>
|
||||
>
|
||||
>
|
||||
extends RedBlackTree<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR, NODE, TREE>
|
||||
export class TreeMultiMap<K = any, V = any, R = object, MK = any, MV = any, MR = object>
|
||||
extends RedBlackTree<K, V, R, MK, MV, MR>
|
||||
implements IBinaryTree<K, V, R, MK, MV, MR>
|
||||
{
|
||||
/**
|
||||
* The constructor function initializes a TreeMultiMap object with optional initial data.
|
||||
|
@ -74,7 +79,10 @@ export class TreeMultiMap<
|
|||
* behavior of the `TreeMultiMap` constructor. It can include properties such as `compareKeys` and
|
||||
* `compareValues`, which are functions used to compare keys and values respectively.
|
||||
*/
|
||||
constructor(keysNodesEntriesOrRaws: Iterable<BTNRep<K, V, NODE>> = [], options?: TreeMultiMapOptions<K, V, R>) {
|
||||
constructor(
|
||||
keysNodesEntriesOrRaws: Iterable<BTNRep<K, V, TreeMultiMapNode<K, V>>> = [],
|
||||
options?: TreeMultiMapOptions<K, V, R>
|
||||
) {
|
||||
super([], options);
|
||||
if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);
|
||||
}
|
||||
|
@ -115,10 +123,10 @@ export class TreeMultiMap<
|
|||
* @param {number} [count] - The `count` parameter represents the number of occurrences of a key in
|
||||
* the tree. It is an optional parameter and is used to keep track of the number of values associated
|
||||
* with a key in the tree.
|
||||
* @returns A new instance of the TreeMultiMapNode class, casted as NODE.
|
||||
* @returns A new instance of the TreeMultiMapNode class, casted as TreeMultiMapNode<K, V>.
|
||||
*/
|
||||
override createNode(key: K, value?: V, color: RBTNColor = 'BLACK', count?: number): NODE {
|
||||
return new TreeMultiMapNode(key, this._isMapMode ? undefined : value, count, color) as NODE;
|
||||
override createNode(key: K, value?: V, color: RBTNColor = 'BLACK', count?: number): TreeMultiMapNode<K, V> {
|
||||
return new TreeMultiMapNode(key, this._isMapMode ? undefined : value, count, color) as TreeMultiMapNode<K, V>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -129,63 +137,26 @@ export class TreeMultiMap<
|
|||
* @returns a new instance of the `TreeMultiMap` class, with the provided options merged with the
|
||||
* existing `iterationType` property. The returned value is casted as `TREE`.
|
||||
*/
|
||||
override createTree(options?: TreeMultiMapOptions<K, V, R>): TREE {
|
||||
return new TreeMultiMap<K, V, R, MK, MV, MR, NODE, TREE>([], {
|
||||
override createTree(options?: TreeMultiMapOptions<K, V, R>) {
|
||||
return new TreeMultiMap<K, V, R, MK, MV, MR>([], {
|
||||
iterationType: this.iterationType,
|
||||
isMapMode: this._isMapMode,
|
||||
specifyComparable: this._specifyComparable,
|
||||
toEntryFn: this._toEntryFn,
|
||||
...options
|
||||
}) as TREE;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function `keyValueNodeEntryRawToNodeAndValue` takes in a key, value, and count and returns a
|
||||
* node based on the input.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {V} [value] - The `value` parameter is an optional value that represents the value
|
||||
* associated with the key in the node. It is used when creating a new node or updating the value of
|
||||
* an existing node.
|
||||
* @param [count=1] - The `count` parameter is an optional parameter that specifies the number of
|
||||
* times the key-value pair should be added to the data structure. If not provided, it defaults to 1.
|
||||
* @returns either a NODE object or undefined.
|
||||
*/
|
||||
protected override _keyValueNodeEntryRawToNodeAndValue(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R,
|
||||
value?: V,
|
||||
count = 1
|
||||
): [NODE | undefined, V | undefined] {
|
||||
if (keyNodeEntryOrRaw === undefined || keyNodeEntryOrRaw === null) return [undefined, undefined];
|
||||
|
||||
if (this.isNode(keyNodeEntryOrRaw)) return [keyNodeEntryOrRaw, value];
|
||||
|
||||
if (this.isEntry(keyNodeEntryOrRaw)) {
|
||||
const [key, entryValue] = keyNodeEntryOrRaw;
|
||||
if (key === undefined || key === null) return [undefined, undefined];
|
||||
const finalValue = value ?? entryValue;
|
||||
if (this.isKey(key)) return [this.createNode(key, finalValue, 'BLACK', count), finalValue];
|
||||
}
|
||||
|
||||
if (this.isRaw(keyNodeEntryOrRaw)) {
|
||||
const [key, entryValue] = this._toEntryFn!(keyNodeEntryOrRaw);
|
||||
const finalValue = value ?? entryValue;
|
||||
if (this.isKey(key)) return [this.createNode(key, finalValue, 'BLACK', count), finalValue];
|
||||
}
|
||||
|
||||
if (this.isKey(keyNodeEntryOrRaw)) return [this.createNode(keyNodeEntryOrRaw, value, 'BLACK', count), value];
|
||||
|
||||
return [undefined, undefined];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The function checks if the input is an instance of the TreeMultiMapNode class.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, NODE>`.
|
||||
* @param {BTNRep<K, V, TreeMultiMapNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, TreeMultiMapNode<K, V>>`.
|
||||
* @returns a boolean value indicating whether the input parameter `keyNodeEntryOrRaw` is
|
||||
* an instance of the `TreeMultiMapNode` class.
|
||||
*/
|
||||
override isNode(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R): keyNodeEntryOrRaw is NODE {
|
||||
override isNode(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, TreeMultiMapNode<K, V>> | R
|
||||
): keyNodeEntryOrRaw is TreeMultiMapNode<K, V> {
|
||||
return keyNodeEntryOrRaw instanceof TreeMultiMapNode;
|
||||
}
|
||||
|
||||
|
@ -195,7 +166,7 @@ export class TreeMultiMap<
|
|||
*
|
||||
* The function overrides the add method of a class and adds a new node to a data structure, updating
|
||||
* the count and returning a boolean indicating success.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The
|
||||
* @param {BTNRep<K, V, TreeMultiMapNode<K, V>> | R} keyNodeEntryOrRaw - The
|
||||
* `keyNodeEntryOrRaw` parameter can accept one of the following types:
|
||||
* @param {V} [value] - The `value` parameter represents the value associated with the key in the
|
||||
* data structure. It is an optional parameter, so it can be omitted if not needed.
|
||||
|
@ -205,7 +176,7 @@ export class TreeMultiMap<
|
|||
* @returns The method is returning a boolean value. It returns true if the addition of the new node
|
||||
* was successful, and false otherwise.
|
||||
*/
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R, value?: V, count = 1): boolean {
|
||||
override add(keyNodeEntryOrRaw: BTNRep<K, V, TreeMultiMapNode<K, V>> | R, value?: V, count = 1): boolean {
|
||||
const [newNode, newValue] = this._keyValueNodeEntryRawToNodeAndValue(keyNodeEntryOrRaw, value, count);
|
||||
const orgCount = newNode?.count || 0;
|
||||
const isSuccessAdded = super.add(newNode, newValue);
|
||||
|
@ -224,21 +195,24 @@ export class TreeMultiMap<
|
|||
*
|
||||
* The function `delete` in TypeScript overrides the deletion operation in a binary tree data
|
||||
* structure, handling cases where nodes have children and maintaining balance in the tree.
|
||||
* @param {BTNRep<K, V, NODE> | R} keyNodeEntryOrRaw - The `predicate`
|
||||
* @param {BTNRep<K, V, TreeMultiMapNode<K, V>> | R} keyNodeEntryOrRaw - The `predicate`
|
||||
* parameter in the `delete` method is used to specify the condition or key based on which a node
|
||||
* should be deleted from the binary tree. It can be a key, a node, or an entry.
|
||||
* @param [ignoreCount=false] - The `ignoreCount` parameter in the `override delete` method is a
|
||||
* boolean flag that determines whether to ignore the count of nodes when performing deletion. If
|
||||
* `ignoreCount` is set to `true`, the method will delete the node regardless of its count. If
|
||||
* `ignoreCount` is `false
|
||||
* @returns The `override delete` method returns an array of `BinaryTreeDeleteResult<NODE>` objects.
|
||||
* @returns The `override delete` method returns an array of `BinaryTreeDeleteResult<TreeMultiMapNode<K, V>>` objects.
|
||||
*/
|
||||
override delete(keyNodeEntryOrRaw: BTNRep<K, V, NODE> | R, ignoreCount = false): BinaryTreeDeleteResult<NODE>[] {
|
||||
override delete(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, TreeMultiMapNode<K, V>> | R,
|
||||
ignoreCount = false
|
||||
): BinaryTreeDeleteResult<TreeMultiMapNode<K, V>>[] {
|
||||
if (keyNodeEntryOrRaw === null) return [];
|
||||
|
||||
const results: BinaryTreeDeleteResult<NODE>[] = [];
|
||||
const results: BinaryTreeDeleteResult<TreeMultiMapNode<K, V>>[] = [];
|
||||
|
||||
let nodeToDelete: OptNode<NODE>;
|
||||
let nodeToDelete: OptNode<TreeMultiMapNode<K, V>>;
|
||||
if (this._isPredicate(keyNodeEntryOrRaw)) nodeToDelete = this.getNode(keyNodeEntryOrRaw);
|
||||
else nodeToDelete = this.isRealNode(keyNodeEntryOrRaw) ? keyNodeEntryOrRaw : this.getNode(keyNodeEntryOrRaw);
|
||||
|
||||
|
@ -247,7 +221,7 @@ export class TreeMultiMap<
|
|||
}
|
||||
|
||||
let originalColor = nodeToDelete.color;
|
||||
let replacementNode: NODE | undefined;
|
||||
let replacementNode: TreeMultiMapNode<K, V> | undefined;
|
||||
|
||||
if (!this.isRealNode(nodeToDelete.left)) {
|
||||
if (nodeToDelete.right !== null) replacementNode = nodeToDelete.right;
|
||||
|
@ -400,71 +374,13 @@ export class TreeMultiMap<
|
|||
* The function overrides the clone method to create a deep copy of a tree object.
|
||||
* @returns The `clone()` method is returning a cloned instance of the `TREE` object.
|
||||
*/
|
||||
override clone(): TREE {
|
||||
override clone() {
|
||||
const cloned = this.createTree();
|
||||
this.bfs(node => cloned.add(node.key, undefined, node.count));
|
||||
if (this._isMapMode) cloned._store = this._store;
|
||||
return cloned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time Complexity: O(1)
|
||||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `_swapProperties` function swaps the properties (key, value, count, color) between two nodes
|
||||
* in a binary search tree.
|
||||
* @param {R | BSTNOptKeyOrNode<K, NODE>} srcNode - The `srcNode` parameter represents the source node
|
||||
* that will be swapped with the `destNode`. It can be either an instance of the `R` class or an
|
||||
* instance of the `BSTNOptKeyOrNode<K, NODE>` class.
|
||||
* @param {R | BSTNOptKeyOrNode<K, NODE>} destNode - The `destNode` parameter represents the destination
|
||||
* node where the properties will be swapped with the source node.
|
||||
* @returns The method is returning the `destNode` after swapping its properties with the `srcNode`.
|
||||
* If either `srcNode` or `destNode` is undefined, it returns undefined.
|
||||
*/
|
||||
protected override _swapProperties(
|
||||
srcNode: R | BSTNOptKeyOrNode<K, NODE>,
|
||||
destNode: R | BSTNOptKeyOrNode<K, NODE>
|
||||
): NODE | undefined {
|
||||
srcNode = this.ensureNode(srcNode);
|
||||
destNode = this.ensureNode(destNode);
|
||||
if (srcNode && destNode) {
|
||||
const { key, value, count, color } = destNode;
|
||||
const tempNode = this.createNode(key, value, color, count);
|
||||
if (tempNode) {
|
||||
tempNode.color = color;
|
||||
|
||||
destNode.key = srcNode.key;
|
||||
if (!this._isMapMode) destNode.value = srcNode.value;
|
||||
destNode.count = srcNode.count;
|
||||
destNode.color = srcNode.color;
|
||||
|
||||
srcNode.key = tempNode.key;
|
||||
if (!this._isMapMode) srcNode.value = tempNode.value;
|
||||
srcNode.count = tempNode.count;
|
||||
srcNode.color = tempNode.color;
|
||||
}
|
||||
|
||||
return destNode;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time Complexity: O(1)
|
||||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function replaces an old node with a new node and updates the count property of the new node.
|
||||
* @param {NODE} oldNode - The `oldNode` parameter is the node that you want to replace in the data
|
||||
* structure.
|
||||
* @param {NODE} newNode - The `newNode` parameter is an instance of the `NODE` class.
|
||||
* @returns The method is returning the result of calling the `_replaceNode` method from the
|
||||
* superclass, which is of type `NODE`.
|
||||
*/
|
||||
protected override _replaceNode(oldNode: NODE, newNode: NODE): NODE {
|
||||
newNode.count = oldNode.count + newNode.count;
|
||||
return super._replaceNode(oldNode, newNode);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `map` function in TypeScript overrides the default behavior to create a new TreeMultiMap with
|
||||
* modified entries based on a provided callback.
|
||||
|
@ -492,4 +408,104 @@ export class TreeMultiMap<
|
|||
}
|
||||
return newTree;
|
||||
}
|
||||
|
||||
/**
|
||||
* The function `keyValueNodeEntryRawToNodeAndValue` takes in a key, value, and count and returns a
|
||||
* node based on the input.
|
||||
* @param {BTNRep<K, V, TreeMultiMapNode<K, V>> | R} keyNodeEntryOrRaw - The parameter
|
||||
* `keyNodeEntryOrRaw` can be of type `R` or `BTNRep<K, V, TreeMultiMapNode<K, V>>`.
|
||||
* @param {V} [value] - The `value` parameter is an optional value that represents the value
|
||||
* associated with the key in the node. It is used when creating a new node or updating the value of
|
||||
* an existing node.
|
||||
* @param [count=1] - The `count` parameter is an optional parameter that specifies the number of
|
||||
* times the key-value pair should be added to the data structure. If not provided, it defaults to 1.
|
||||
* @returns either a TreeMultiMapNode<K, V> object or undefined.
|
||||
*/
|
||||
protected override _keyValueNodeEntryRawToNodeAndValue(
|
||||
keyNodeEntryOrRaw: BTNRep<K, V, TreeMultiMapNode<K, V>> | R,
|
||||
value?: V,
|
||||
count = 1
|
||||
): [TreeMultiMapNode<K, V> | undefined, V | undefined] {
|
||||
if (keyNodeEntryOrRaw === undefined || keyNodeEntryOrRaw === null) return [undefined, undefined];
|
||||
|
||||
if (this.isNode(keyNodeEntryOrRaw)) return [keyNodeEntryOrRaw, value];
|
||||
|
||||
if (this.isEntry(keyNodeEntryOrRaw)) {
|
||||
const [key, entryValue] = keyNodeEntryOrRaw;
|
||||
if (key === undefined || key === null) return [undefined, undefined];
|
||||
const finalValue = value ?? entryValue;
|
||||
if (this.isKey(key)) return [this.createNode(key, finalValue, 'BLACK', count), finalValue];
|
||||
}
|
||||
|
||||
if (this.isRaw(keyNodeEntryOrRaw)) {
|
||||
const [key, entryValue] = this._toEntryFn!(keyNodeEntryOrRaw);
|
||||
const finalValue = value ?? entryValue;
|
||||
if (this.isKey(key)) return [this.createNode(key, finalValue, 'BLACK', count), finalValue];
|
||||
}
|
||||
|
||||
if (this.isKey(keyNodeEntryOrRaw)) return [this.createNode(keyNodeEntryOrRaw, value, 'BLACK', count), value];
|
||||
|
||||
return [undefined, undefined];
|
||||
}
|
||||
|
||||
/**
|
||||
* Time Complexity: O(1)
|
||||
* Space Complexity: O(1)
|
||||
*
|
||||
* The `_swapProperties` function swaps the properties (key, value, count, color) between two nodes
|
||||
* in a binary search tree.
|
||||
* @param {R | BSTNOptKeyOrNode<K, TreeMultiMapNode<K, V>>} srcNode - The `srcNode` parameter represents the source node
|
||||
* that will be swapped with the `destNode`. It can be either an instance of the `R` class or an
|
||||
* instance of the `BSTNOptKeyOrNode<K, TreeMultiMapNode<K, V>>` class.
|
||||
* @param {R | BSTNOptKeyOrNode<K, TreeMultiMapNode<K, V>>} destNode - The `destNode` parameter represents the destination
|
||||
* node where the properties will be swapped with the source node.
|
||||
* @returns The method is returning the `destNode` after swapping its properties with the `srcNode`.
|
||||
* If either `srcNode` or `destNode` is undefined, it returns undefined.
|
||||
*/
|
||||
protected override _swapProperties(
|
||||
srcNode: R | BSTNOptKeyOrNode<K, TreeMultiMapNode<K, V>>,
|
||||
destNode: R | BSTNOptKeyOrNode<K, TreeMultiMapNode<K, V>>
|
||||
): TreeMultiMapNode<K, V> | undefined {
|
||||
srcNode = this.ensureNode(srcNode);
|
||||
destNode = this.ensureNode(destNode);
|
||||
if (srcNode && destNode) {
|
||||
const { key, value, count, color } = destNode;
|
||||
const tempNode = this.createNode(key, value, color, count);
|
||||
if (tempNode) {
|
||||
tempNode.color = color;
|
||||
|
||||
destNode.key = srcNode.key;
|
||||
if (!this._isMapMode) destNode.value = srcNode.value;
|
||||
destNode.count = srcNode.count;
|
||||
destNode.color = srcNode.color;
|
||||
|
||||
srcNode.key = tempNode.key;
|
||||
if (!this._isMapMode) srcNode.value = tempNode.value;
|
||||
srcNode.count = tempNode.count;
|
||||
srcNode.color = tempNode.color;
|
||||
}
|
||||
|
||||
return destNode;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time Complexity: O(1)
|
||||
* Space Complexity: O(1)
|
||||
*
|
||||
* The function replaces an old node with a new node and updates the count property of the new node.
|
||||
* @param {TreeMultiMapNode<K, V>} oldNode - The `oldNode` parameter is the node that you want to replace in the data
|
||||
* structure.
|
||||
* @param {TreeMultiMapNode<K, V>} newNode - The `newNode` parameter is an instance of the `TreeMultiMapNode<K, V>` class.
|
||||
* @returns The method is returning the result of calling the `_replaceNode` method from the
|
||||
* superclass, which is of type `TreeMultiMapNode<K, V>`.
|
||||
*/
|
||||
protected override _replaceNode(
|
||||
oldNode: TreeMultiMapNode<K, V>,
|
||||
newNode: TreeMultiMapNode<K, V>
|
||||
): TreeMultiMapNode<K, V> {
|
||||
newNode.count = oldNode.count + newNode.count;
|
||||
return super._replaceNode(oldNode, newNode);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,30 +1,16 @@
|
|||
import { BinaryTree, BinaryTreeNode } from '../data-structures';
|
||||
import type {
|
||||
BinaryTreeDeleteResult,
|
||||
BinaryTreeNested,
|
||||
BinaryTreeNodeNested,
|
||||
BinaryTreeOptions,
|
||||
BTNRep,
|
||||
NodePredicate
|
||||
} from '../types';
|
||||
import { BinaryTreeNode } from '../data-structures';
|
||||
import type { BinaryTreeDeleteResult, BinaryTreeOptions, BTNRep, NodePredicate } from '../types';
|
||||
|
||||
export interface IBinaryTree<
|
||||
K = any,
|
||||
V = any,
|
||||
R = object,
|
||||
MK = any,
|
||||
MV = any,
|
||||
MR = object,
|
||||
NODE extends BinaryTreeNode<K, V, NODE> = BinaryTreeNodeNested<K, V>,
|
||||
TREE extends BinaryTree<K, V, R, MK, MV, MR, NODE, TREE> = BinaryTreeNested<K, V, R, MK, MV, MR, NODE>
|
||||
> {
|
||||
createNode(key: K, value?: NODE['value']): NODE;
|
||||
export interface IBinaryTree<K = any, V = any, R = object, MK = any, MV = any, MR = object> {
|
||||
createNode(key: K, value?: BinaryTreeNode['value']): BinaryTreeNode;
|
||||
|
||||
createTree(options?: Partial<BinaryTreeOptions<K, V, R>>): TREE;
|
||||
createTree(options?: Partial<BinaryTreeOptions<K, V, R>>): IBinaryTree<K, V, R, MK, MV, MR>;
|
||||
|
||||
add(keyOrNodeOrEntryOrRawElement: BTNRep<K, V, NODE>, value?: V, count?: number): boolean;
|
||||
add(keyOrNodeOrEntryOrRawElement: BTNRep<K, V, BinaryTreeNode<K, V>>, value?: V, count?: number): boolean;
|
||||
|
||||
addMany(nodes: Iterable<BTNRep<K, V, NODE>>, values?: Iterable<V | undefined>): boolean[];
|
||||
addMany(nodes: Iterable<BTNRep<K, V, BinaryTreeNode<K, V>>>, values?: Iterable<V | undefined>): boolean[];
|
||||
|
||||
delete(predicate: R | BTNRep<K, V, NODE> | NodePredicate<NODE>): BinaryTreeDeleteResult<NODE>[];
|
||||
delete(
|
||||
predicate: R | BTNRep<K, V, BinaryTreeNode<K, V>> | NodePredicate<BinaryTreeNode<K, V>>
|
||||
): BinaryTreeDeleteResult<BinaryTreeNode<K, V>>[];
|
||||
}
|
||||
|
|
|
@ -1,8 +1,3 @@
|
|||
import { AVLTreeMultiMap, AVLTreeMultiMapNode } from '../../../data-structures';
|
||||
import type { AVLTreeOptions } from './avl-tree';
|
||||
|
||||
export type AVLTreeMultiMapNodeNested<K, V> = AVLTreeMultiMapNode<K, V, AVLTreeMultiMapNode<K, V, AVLTreeMultiMapNode<K, V, any>>>
|
||||
|
||||
export type AVLTreeMultiMapNested<K, V, R, MK, MV, MR, NODE extends AVLTreeMultiMapNode<K, V, NODE>> = AVLTreeMultiMap<K, V, R, MK, MV, MR, NODE, AVLTreeMultiMap<K, V, R, MK, MV, MR, NODE, AVLTreeMultiMap<K, V, R, MK, MV, MR, NODE, any>>>
|
||||
|
||||
export type AVLTreeMultiMapOptions<K, V, R> = AVLTreeOptions<K, V, R> & {}
|
||||
|
|
|
@ -1,8 +1,3 @@
|
|||
import { AVLTree, AVLTreeNode } from '../../../data-structures';
|
||||
import { BSTOptions } from './bst';
|
||||
|
||||
export type AVLTreeNodeNested<K, V> = AVLTreeNode<K, V, AVLTreeNode<K, V, AVLTreeNode<K, V, any>>>
|
||||
|
||||
export type AVLTreeNested<K, V, R,MK, MV, MR, NODE extends AVLTreeNode<K, V, NODE>> = AVLTree<K, V, R,MK, MV, MR, NODE, AVLTree<K, V, R,MK, MV, MR, NODE, AVLTree<K, V, R,MK, MV, MR, NODE, any>>>
|
||||
|
||||
export type AVLTreeOptions<K, V, R> = BSTOptions<K, V, R> & {};
|
||||
|
|
|
@ -1,11 +1,6 @@
|
|||
import { BinaryTree, BinaryTreeNode } from '../../../data-structures';
|
||||
import { IterationType, OptValue } from '../../common';
|
||||
import { DFSOperation } from '../../../common';
|
||||
|
||||
export type BinaryTreeNodeNested<K, V> = BinaryTreeNode<K, V, BinaryTreeNode<K, V, BinaryTreeNode<K, V, any>>>
|
||||
|
||||
export type BinaryTreeNested<K, V, R, MK, MV, MR, NODE extends BinaryTreeNode<K, V, NODE>> = BinaryTree<K, V, R, MK, MV, MR, NODE,BinaryTree<K, V, R, MK, MV, MR, NODE,BinaryTree<K, V, R, MK, MV, MR, NODE,any>>>
|
||||
|
||||
export type ToEntryFn<K, V, R> = (rawElement: R) => BTNEntry<K, V>;
|
||||
|
||||
export type BinaryTreeOptions<K, V, R> = {
|
||||
|
|
|
@ -1,10 +1,6 @@
|
|||
import { BST, BSTNode } from '../../../data-structures';
|
||||
import type { BinaryTreeOptions } from './binary-tree';
|
||||
import { Comparable } from '../../utils';
|
||||
|
||||
export type BSTNodeNested<K, V> = BSTNode<K, V, BSTNode<K, V, BSTNode<K, V, any>>>
|
||||
|
||||
export type BSTNested<K, V, R,MK, MV, MR, NODE extends BSTNode<K, V, NODE>> = BST<K, V, R,MK, MV, MR, NODE,BST<K, V, R,MK, MV, MR, NODE,BST<K, V, R,MK, MV, MR, NODE, any>>>
|
||||
import { OptValue } from '../../common';
|
||||
|
||||
export type BSTOptions<K, V, R> = BinaryTreeOptions<K, V, R> & {
|
||||
specifyComparable?: (key: K) => Comparable
|
||||
|
@ -15,5 +11,9 @@ export type BSTNOptKey<K> = K | undefined;
|
|||
|
||||
export type OptNode<NODE> = NODE | undefined;
|
||||
|
||||
export type BSTNEntry<K, V> = [BSTNOptKey<K>, OptValue<V>];
|
||||
|
||||
export type BSTNOptKeyOrNode<K, NODE> = BSTNOptKey<K> | NODE;
|
||||
|
||||
export type BSTNRep<K, V, NODE> = BSTNEntry<K, V> | BSTNOptKeyOrNode<K, NODE>;
|
||||
|
||||
|
|
|
@ -1,10 +1,5 @@
|
|||
import { RedBlackTree, RedBlackTreeNode } from '../../../data-structures';
|
||||
import type { BSTOptions } from "./bst";
|
||||
import type { BSTOptions } from './bst';
|
||||
|
||||
export type RBTNColor = 'RED' | 'BLACK';
|
||||
|
||||
export type RedBlackTreeNodeNested<K, V> = RedBlackTreeNode<K, V, RedBlackTreeNode<K, V, RedBlackTreeNode<K, V, any>>>
|
||||
|
||||
export type RedBlackTreeNested<K, V, R, MK, MV, MR, NODE extends RedBlackTreeNode<K, V, NODE>> = RedBlackTree<K, V, R, MK, MV, MR, NODE, RedBlackTree<K, V, R, MK, MV, MR, NODE, RedBlackTree<K, V, R, MK, MV, MR, NODE, any>>>
|
||||
|
||||
export type RedBlackTreeOptions<K, V, R> = BSTOptions<K, V, R> & {};
|
||||
|
|
|
@ -1,8 +1,3 @@
|
|||
import { TreeMultiMap, TreeMultiMapNode } from '../../../data-structures';
|
||||
import type { RedBlackTreeOptions } from './rb-tree';
|
||||
|
||||
export type TreeMultiMapNodeNested<K, V> = TreeMultiMapNode<K, V, TreeMultiMapNode<K, V, TreeMultiMapNode<K, V, any>>>
|
||||
|
||||
export type TreeMultiMapNested<K, V, R, MK, MV, MR, NODE extends TreeMultiMapNode<K, V, NODE>> = TreeMultiMap<K, V, R, MK, MV, MR, NODE, TreeMultiMap<K, V, R, MK, MV, MR, NODE,TreeMultiMap<K, V, R, MK, MV, MR, NODE, any>>>
|
||||
|
||||
export type TreeMultiMapOptions<K, V, R> = RedBlackTreeOptions<K, V, R> & {}
|
||||
|
|
|
@ -3,7 +3,7 @@ import { AVLTree } from 'data-structure-typed';
|
|||
describe('AVL Tree Test from data-structure-typed', () => {
|
||||
it('should perform various operations on a AVL Tree from data-structure-typed', () => {
|
||||
const keys = [11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5];
|
||||
const tree = new AVLTree<number>();
|
||||
const tree = new AVLTree<number>([], { isMapMode: false });
|
||||
|
||||
for (const i of keys) tree.add([i, i]);
|
||||
|
||||
|
|
|
@ -48,7 +48,7 @@ describe('AVL Tree Test', () => {
|
|||
expect(lesserSum).toBe(45);
|
||||
|
||||
// node15 has type problem. After the uniform design, the generics of containers (DirectedGraph, BST) are based on the type of value. However, this design has a drawback: when I attempt to inherit from the Vertex or BSTNode classes, the types of the results obtained by all methods are those of the parent class.
|
||||
expect(node15?.value).toBe(15);
|
||||
expect(node15?.value).toBe(undefined);
|
||||
|
||||
const dfs = tree.dfs(node => node, 'IN');
|
||||
expect(dfs[0].key).toBe(1);
|
||||
|
|
|
@ -27,7 +27,7 @@ describe('Individual package BST operations test', () => {
|
|||
expect(nodeVal9?.key).toBe(undefined);
|
||||
|
||||
const nodeVal11 = bst.getNode(node => node.value === 11);
|
||||
expect(nodeVal11?.key).toBe(11);
|
||||
expect(nodeVal11?.key).toBe(undefined);
|
||||
|
||||
const leftMost = bst.getLeftMost(node => node);
|
||||
expect(leftMost?.key).toBe(1);
|
||||
|
@ -186,7 +186,7 @@ describe('Individual package BST operations test', () => {
|
|||
});
|
||||
|
||||
it('should perform various operations on a Binary Search Tree with object values', () => {
|
||||
const objBST = new BST<number, { key: number; keyA: number }>();
|
||||
const objBST = new BST<number, { key: number; keyA: number }>([], { isMapMode: false });
|
||||
expect(objBST).toBeInstanceOf(BST);
|
||||
objBST.add([11, { key: 11, keyA: 11 }]);
|
||||
objBST.add([3, { key: 3, keyA: 3 }]);
|
||||
|
|
143
test/integration/compile.js
Normal file
143
test/integration/compile.js
Normal file
|
@ -0,0 +1,143 @@
|
|||
'use strict';
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
var data_structure_typed_1 = require('data-structure-typed');
|
||||
var orgArr = [6, 1, 2, 7, 5, 3, 4, 9, 8];
|
||||
var orgStrArr = ['trie', 'trial', 'trick', 'trip', 'tree', 'trend', 'triangle', 'track', 'trace', 'transmit'];
|
||||
var entries = [
|
||||
[6, '6'],
|
||||
[1, '1'],
|
||||
[2, '2'],
|
||||
[7, '7'],
|
||||
[5, '5'],
|
||||
[3, '3'],
|
||||
[4, '4'],
|
||||
[9, '9'],
|
||||
[8, '8']
|
||||
];
|
||||
var queue = new data_structure_typed_1.Queue(orgArr);
|
||||
queue.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
var deque = new data_structure_typed_1.Deque(orgArr);
|
||||
deque.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
var sList = new data_structure_typed_1.SinglyLinkedList(orgArr);
|
||||
sList.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
var dList = new data_structure_typed_1.DoublyLinkedList(orgArr);
|
||||
dList.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
var stack = new data_structure_typed_1.Stack(orgArr);
|
||||
stack.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
var minHeap = new data_structure_typed_1.MinHeap(orgArr);
|
||||
minHeap.print();
|
||||
// [1, 5, 2, 7, 6, 3, 4, 9, 8]
|
||||
var maxPQ = new data_structure_typed_1.MaxPriorityQueue(orgArr);
|
||||
maxPQ.print();
|
||||
// [9, 8, 4, 7, 5, 2, 3, 1, 6]
|
||||
var biTree = new data_structure_typed_1.BinaryTree(entries);
|
||||
biTree.print();
|
||||
// ___6___
|
||||
// / \
|
||||
// ___1_ _2_
|
||||
// / \ / \
|
||||
// _7_ 5 3 4
|
||||
// / \
|
||||
// 9 8
|
||||
var bst = new data_structure_typed_1.BST(entries);
|
||||
bst.print();
|
||||
// _____5___
|
||||
// / \
|
||||
// _2_ _7_
|
||||
// / \ / \
|
||||
// 1 3_ 6 8_
|
||||
// \ \
|
||||
// 4 9
|
||||
var rbTree = new data_structure_typed_1.RedBlackTree(entries);
|
||||
rbTree.print();
|
||||
// ___4___
|
||||
// / \
|
||||
// _2_ _6___
|
||||
// / \ / \
|
||||
// 1 3 5 _8_
|
||||
// / \
|
||||
// 7 9
|
||||
var avl = new data_structure_typed_1.AVLTree(entries);
|
||||
avl.print();
|
||||
// ___4___
|
||||
// / \
|
||||
// _2_ _6___
|
||||
// / \ / \
|
||||
// 1 3 5 _8_
|
||||
// / \
|
||||
// 7 9
|
||||
var treeMulti = new data_structure_typed_1.TreeMultiMap(entries);
|
||||
treeMulti.print();
|
||||
// ___4___
|
||||
// / \
|
||||
// _2_ _6___
|
||||
// / \ / \
|
||||
// 1 3 5 _8_
|
||||
// / \
|
||||
// 7 9
|
||||
var hm = new data_structure_typed_1.HashMap(entries);
|
||||
hm.print();
|
||||
// [[6, "6"], [1, "1"], [2, "2"], [7, "7"], [5, "5"], [3, "3"], [4, "4"], [9, "9"], [8, "8"]]
|
||||
var rbTreeH = new data_structure_typed_1.RedBlackTree(hm);
|
||||
rbTreeH.print();
|
||||
// ___4___
|
||||
// / \
|
||||
// _2_ _6___
|
||||
// / \ / \
|
||||
// 1 3 5 _8_
|
||||
// / \
|
||||
// 7 9
|
||||
var pq = new data_structure_typed_1.MinPriorityQueue(orgArr);
|
||||
pq.print();
|
||||
// [1, 5, 2, 7, 6, 3, 4, 9, 8]
|
||||
var bst1 = new data_structure_typed_1.BST(pq);
|
||||
bst1.print();
|
||||
// _____5___
|
||||
// / \
|
||||
// _2_ _7_
|
||||
// / \ / \
|
||||
// 1 3_ 6 8_
|
||||
// \ \
|
||||
// 4 9
|
||||
var dq1 = new data_structure_typed_1.Deque(orgArr);
|
||||
dq1.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
var rbTree1 = new data_structure_typed_1.RedBlackTree(dq1);
|
||||
rbTree1.print();
|
||||
// _____5___
|
||||
// / \
|
||||
// _2___ _7___
|
||||
// / \ / \
|
||||
// 1 _4 6 _9
|
||||
// / /
|
||||
// 3 8
|
||||
var trie2 = new data_structure_typed_1.Trie(orgStrArr);
|
||||
trie2.print();
|
||||
// ['trie', 'trial', 'triangle', 'trick', 'trip', 'tree', 'trend', 'track', 'trace', 'transmit']
|
||||
var heap2 = new data_structure_typed_1.Heap(trie2, {
|
||||
comparator: function (a, b) {
|
||||
return Number(a) - Number(b);
|
||||
}
|
||||
});
|
||||
heap2.print();
|
||||
// ['transmit', 'trace', 'tree', 'trend', 'track', 'trial', 'trip', 'trie', 'trick', 'triangle']
|
||||
var dq2 = new data_structure_typed_1.Deque(heap2);
|
||||
dq2.print();
|
||||
// ['transmit', 'trace', 'tree', 'trend', 'track', 'trial', 'trip', 'trie', 'trick', 'triangle']
|
||||
var entries2 = dq2.map(function (el, i) {
|
||||
return [i, el];
|
||||
});
|
||||
var avl2 = new data_structure_typed_1.AVLTree(entries2);
|
||||
avl2.print();
|
||||
// ___3_______
|
||||
// / \
|
||||
// _1_ ___7_
|
||||
// / \ / \
|
||||
// 0 2 _5_ 8_
|
||||
// / \ \
|
||||
// 4 6 9
|
171
test/integration/compile.ts
Normal file
171
test/integration/compile.ts
Normal file
|
@ -0,0 +1,171 @@
|
|||
import {
|
||||
AVLTree,
|
||||
BinaryTree,
|
||||
BST,
|
||||
Deque,
|
||||
DoublyLinkedList,
|
||||
HashMap,
|
||||
Heap,
|
||||
MaxPriorityQueue,
|
||||
MinHeap,
|
||||
MinPriorityQueue,
|
||||
Queue,
|
||||
RedBlackTree,
|
||||
SinglyLinkedList,
|
||||
Stack,
|
||||
TreeMultiMap,
|
||||
Trie
|
||||
} from 'data-structure-typed';
|
||||
|
||||
const orgArr = [6, 1, 2, 7, 5, 3, 4, 9, 8];
|
||||
const orgStrArr = ['trie', 'trial', 'trick', 'trip', 'tree', 'trend', 'triangle', 'track', 'trace', 'transmit'];
|
||||
const entries: [number, string][] = [
|
||||
[6, '6'],
|
||||
[1, '1'],
|
||||
[2, '2'],
|
||||
[7, '7'],
|
||||
[5, '5'],
|
||||
[3, '3'],
|
||||
[4, '4'],
|
||||
[9, '9'],
|
||||
[8, '8']
|
||||
];
|
||||
|
||||
const queue = new Queue(orgArr);
|
||||
queue.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
|
||||
const deque = new Deque(orgArr);
|
||||
deque.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
|
||||
const sList = new SinglyLinkedList(orgArr);
|
||||
sList.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
|
||||
const dList = new DoublyLinkedList(orgArr);
|
||||
dList.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
|
||||
const stack = new Stack(orgArr);
|
||||
stack.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
|
||||
const minHeap = new MinHeap(orgArr);
|
||||
minHeap.print();
|
||||
// [1, 5, 2, 7, 6, 3, 4, 9, 8]
|
||||
|
||||
const maxPQ = new MaxPriorityQueue(orgArr);
|
||||
maxPQ.print();
|
||||
// [9, 8, 4, 7, 5, 2, 3, 1, 6]
|
||||
|
||||
const biTree = new BinaryTree(entries);
|
||||
biTree.print();
|
||||
// ___6___
|
||||
// / \
|
||||
// ___1_ _2_
|
||||
// / \ / \
|
||||
// _7_ 5 3 4
|
||||
// / \
|
||||
// 9 8
|
||||
|
||||
const bst = new BST(entries);
|
||||
bst.print();
|
||||
// _____5___
|
||||
// / \
|
||||
// _2_ _7_
|
||||
// / \ / \
|
||||
// 1 3_ 6 8_
|
||||
// \ \
|
||||
// 4 9
|
||||
|
||||
const rbTree = new RedBlackTree(entries);
|
||||
rbTree.print();
|
||||
// ___4___
|
||||
// / \
|
||||
// _2_ _6___
|
||||
// / \ / \
|
||||
// 1 3 5 _8_
|
||||
// / \
|
||||
// 7 9
|
||||
|
||||
const avl = new AVLTree(entries);
|
||||
avl.print();
|
||||
// ___4___
|
||||
// / \
|
||||
// _2_ _6___
|
||||
// / \ / \
|
||||
// 1 3 5 _8_
|
||||
// / \
|
||||
// 7 9
|
||||
|
||||
const treeMulti = new TreeMultiMap(entries);
|
||||
treeMulti.print();
|
||||
// ___4___
|
||||
// / \
|
||||
// _2_ _6___
|
||||
// / \ / \
|
||||
// 1 3 5 _8_
|
||||
// / \
|
||||
// 7 9
|
||||
|
||||
const hm = new HashMap(entries);
|
||||
hm.print();
|
||||
// [[6, "6"], [1, "1"], [2, "2"], [7, "7"], [5, "5"], [3, "3"], [4, "4"], [9, "9"], [8, "8"]]
|
||||
|
||||
const rbTreeH = new RedBlackTree(hm);
|
||||
rbTreeH.print();
|
||||
// ___4___
|
||||
// / \
|
||||
// _2_ _6___
|
||||
// / \ / \
|
||||
// 1 3 5 _8_
|
||||
// / \
|
||||
// 7 9
|
||||
|
||||
const pq = new MinPriorityQueue(orgArr);
|
||||
pq.print();
|
||||
// [1, 5, 2, 7, 6, 3, 4, 9, 8]
|
||||
|
||||
const bst1 = new BST(pq);
|
||||
bst1.print();
|
||||
// _____5___
|
||||
// / \
|
||||
// _2_ _7_
|
||||
// / \ / \
|
||||
// 1 3_ 6 8_
|
||||
// \ \
|
||||
// 4 9
|
||||
|
||||
const dq1 = new Deque(orgArr);
|
||||
dq1.print();
|
||||
// [6, 1, 2, 7, 5, 3, 4, 9, 8]
|
||||
const rbTree1 = new RedBlackTree(dq1);
|
||||
rbTree1.print();
|
||||
// _____5___
|
||||
// / \
|
||||
// _2___ _7___
|
||||
// / \ / \
|
||||
// 1 _4 6 _9
|
||||
// / /
|
||||
// 3 8
|
||||
|
||||
const trie2 = new Trie(orgStrArr);
|
||||
trie2.print();
|
||||
// ['trie', 'trial', 'triangle', 'trick', 'trip', 'tree', 'trend', 'track', 'trace', 'transmit']
|
||||
const heap2 = new Heap(trie2, { comparator: (a, b) => Number(a) - Number(b) });
|
||||
heap2.print();
|
||||
// ['transmit', 'trace', 'tree', 'trend', 'track', 'trial', 'trip', 'trie', 'trick', 'triangle']
|
||||
const dq2 = new Deque(heap2);
|
||||
dq2.print();
|
||||
// ['transmit', 'trace', 'tree', 'trend', 'track', 'trial', 'trip', 'trie', 'trick', 'triangle']
|
||||
const entries2 = dq2.map((el, i) => [i, el]);
|
||||
const avl2 = new AVLTree(entries2);
|
||||
avl2.print();
|
||||
// ___3_______
|
||||
// / \
|
||||
// _1_ ___7_
|
||||
// / \ / \
|
||||
// 0 2 _5_ 8_
|
||||
// / \ \
|
||||
// 4 6 9
|
|
@ -12,7 +12,7 @@
|
|||
|
||||
<script src='https://unpkg.com/js-sdsl@4.4.2/dist/umd/js-sdsl.js'></script>
|
||||
<script>
|
||||
const logPerf = function (label = 'function running cost', fn, args, thisArg) {
|
||||
const logPerf = function(label = 'function running cost', fn, args, thisArg) {
|
||||
const start = performance.now();
|
||||
let result;
|
||||
if (thisArg) {
|
||||
|
@ -23,7 +23,7 @@
|
|||
else result = fn();
|
||||
}
|
||||
console.log(`${(performance.now() - start).toFixed(2)} ms, ${label}, ${result}`);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
|
@ -44,7 +44,7 @@
|
|||
for (let i = 0; i < n; i++) {
|
||||
queue.push(i);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
let last = 0;
|
||||
|
||||
|
@ -52,7 +52,7 @@
|
|||
for (let i = 0; i < n; i++) {
|
||||
last = queue.shift();
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
|
@ -80,7 +80,7 @@
|
|||
const tree = new BinaryTree();
|
||||
tree.add(3);
|
||||
tree.add(12);
|
||||
tree.addMany([1, 6, 9, 8, 5, 2, 3, 4, 7])
|
||||
tree.addMany([1, 6, 9, 8, 5, 2, 3, 4, 7]);
|
||||
tree.add(10);
|
||||
console.log(tree.isPerfectlyBalanced(), `tree.isPerfectlyBalanced()`);
|
||||
tree.print(undefined, { isShowUndefined: true });
|
||||
|
@ -112,7 +112,7 @@
|
|||
console.log((performance.now() - tS).toFixed(2), `RedBlackTree ${n.toLocaleString()} add`);
|
||||
console.log(`rbTree.size`, rbTree.size);
|
||||
for (let i = 0; i < n - 8; i++) {
|
||||
rbTree.delete(i)
|
||||
rbTree.delete(i);
|
||||
}
|
||||
rbTree.print(rbTree.root, { isShowRedBlackNIL: true });
|
||||
const cS = performance.now();
|
||||
|
@ -181,34 +181,34 @@
|
|||
|
||||
const objBST = new BST();
|
||||
|
||||
objBST.add(11, { "name": "Pablo", "age": 15 });
|
||||
objBST.add(3, { "name": "Kirk", "age": 1 });
|
||||
objBST.add(11, { 'name': 'Pablo', 'age': 15 });
|
||||
objBST.add(3, { 'name': 'Kirk', 'age': 1 });
|
||||
|
||||
objBST.addMany([15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5], [
|
||||
{ "name": "Alice", "age": 15 },
|
||||
{ "name": "Bob", "age": 1 },
|
||||
{ "name": "Charlie", "age": 8 },
|
||||
{ "name": "David", "age": 13 },
|
||||
{ "name": "Emma", "age": 16 },
|
||||
{ "name": "Frank", "age": 2 },
|
||||
{ "name": "Grace", "age": 6 },
|
||||
{ "name": "Hannah", "age": 9 },
|
||||
{ "name": "Isaac", "age": 12 },
|
||||
{ "name": "Jack", "age": 14 },
|
||||
{ "name": "Katie", "age": 4 },
|
||||
{ "name": "Liam", "age": 7 },
|
||||
{ "name": "Mia", "age": 10 },
|
||||
{ "name": "Noah", "age": 5 }
|
||||
{ 'name': 'Alice', 'age': 15 },
|
||||
{ 'name': 'Bob', 'age': 1 },
|
||||
{ 'name': 'Charlie', 'age': 8 },
|
||||
{ 'name': 'David', 'age': 13 },
|
||||
{ 'name': 'Emma', 'age': 16 },
|
||||
{ 'name': 'Frank', 'age': 2 },
|
||||
{ 'name': 'Grace', 'age': 6 },
|
||||
{ 'name': 'Hannah', 'age': 9 },
|
||||
{ 'name': 'Isaac', 'age': 12 },
|
||||
{ 'name': 'Jack', 'age': 14 },
|
||||
{ 'name': 'Katie', 'age': 4 },
|
||||
{ 'name': 'Liam', 'age': 7 },
|
||||
{ 'name': 'Mia', 'age': 10 },
|
||||
{ 'name': 'Noah', 'age': 5 }
|
||||
]
|
||||
);
|
||||
objBST.print()
|
||||
objBST.print();
|
||||
|
||||
objBST.delete(11);
|
||||
objBST.print()
|
||||
objBST.print();
|
||||
|
||||
|
||||
const rbTree = new RedBlackTree();
|
||||
rbTree.addMany([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5])
|
||||
rbTree.addMany([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);
|
||||
rbTree.isAVLBalanced(); // true
|
||||
rbTree.delete(10);
|
||||
rbTree.isAVLBalanced(); // true
|
||||
|
@ -216,16 +216,16 @@
|
|||
rbTree.print();
|
||||
|
||||
rbTree.delete(14);
|
||||
rbTree.print()
|
||||
rbTree.print();
|
||||
|
||||
const avlTree = new AVLTree();
|
||||
avlTree.addMany([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5])
|
||||
avlTree.addMany([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);
|
||||
avlTree.isAVLBalanced(); // true
|
||||
avlTree.delete(10);
|
||||
avlTree.isAVLBalanced(); // true
|
||||
avlTree.print()
|
||||
avlTree.print();
|
||||
avlTree.delete(14);
|
||||
avlTree.print()
|
||||
avlTree.print();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
|
@ -250,7 +250,7 @@
|
|||
Trie
|
||||
} = dataStructureTyped;
|
||||
const orgArr = [6, 1, 2, 7, 5, 3, 4, 9, 8];
|
||||
const orgStrArr = ["trie", "trial", "trick", "trip", "tree", "trend", "triangle", "track", "trace", "transmit"];
|
||||
const orgStrArr = ['trie', 'trial', 'trick', 'trip', 'tree', 'trend', 'triangle', 'track', 'trace', 'transmit'];
|
||||
const entries = [[6, 6], [1, 1], [2, 2], [7, 7], [5, 5], [3, 3], [4, 4], [9, 9], [8, 8]];
|
||||
|
||||
const queue = new Queue(orgArr);
|
||||
|
@ -327,7 +327,7 @@
|
|||
// 7 9
|
||||
|
||||
const hm = new HashMap(entries);
|
||||
hm.print() // [[6, 6], [1, 1], [2, 2], [7, 7], [5, 5], [3, 3], [4, 4], [9, 9], [8, 8]]
|
||||
hm.print(); // [[6, 6], [1, 1], [2, 2], [7, 7], [5, 5], [3, 3], [4, 4], [9, 9], [8, 8]]
|
||||
|
||||
const rbTreeH = new RedBlackTree(hm);
|
||||
rbTreeH.print();
|
||||
|
@ -408,39 +408,39 @@
|
|||
|
||||
const minNumHeap = new dataStructureTyped.MinHeap([1, 6, 2, 0, 5]);
|
||||
minNumHeap.add(9);
|
||||
minNumHeap.has(1) // true
|
||||
minNumHeap.has(2) // true
|
||||
minNumHeap.poll() // 0
|
||||
minNumHeap.poll() // 1
|
||||
minNumHeap.peek() // 2
|
||||
minNumHeap.has(1); // true
|
||||
minNumHeap.has(2); // true
|
||||
minNumHeap.poll(); // 0
|
||||
minNumHeap.poll(); // 1
|
||||
minNumHeap.peek(); // 2
|
||||
minNumHeap.has(1); // false
|
||||
minNumHeap.has(2); // true
|
||||
|
||||
const arrFromHeap = minNumHeap.toArray();
|
||||
arrFromHeap.length // 4
|
||||
arrFromHeap[0] // 2
|
||||
arrFromHeap[1] // 5
|
||||
arrFromHeap[2] // 9
|
||||
arrFromHeap[3] // 6
|
||||
minNumHeap.sort() // [2, 5, 6, 9]
|
||||
arrFromHeap.length; // 4
|
||||
arrFromHeap[0]; // 2
|
||||
arrFromHeap[1]; // 5
|
||||
arrFromHeap[2]; // 9
|
||||
arrFromHeap[3]; // 6
|
||||
minNumHeap.sort(); // [2, 5, 6, 9]
|
||||
|
||||
const maxHeap = new dataStructureTyped.MaxHeap([], { comparator: (a, b) => b.keyA - a.keyA });
|
||||
const obj1 = { keyA: 'a1' }, obj6 = { keyA: 'a6' }, obj5 = { keyA: 'a5' }, obj2 = { keyA: 'a2' },
|
||||
obj0 = { keyA: 'a0' }, obj9 = { keyA: 'a9' };
|
||||
|
||||
maxHeap.add(obj1);
|
||||
maxHeap.has(obj1) // true
|
||||
maxHeap.has(obj9) // false
|
||||
maxHeap.has(obj1); // true
|
||||
maxHeap.has(obj9); // false
|
||||
maxHeap.add(obj6);
|
||||
maxHeap.has(obj6) // true
|
||||
maxHeap.has(obj6); // true
|
||||
maxHeap.add(obj5);
|
||||
maxHeap.add(obj2);
|
||||
maxHeap.add(obj0);
|
||||
maxHeap.add(obj9);
|
||||
maxHeap.has(obj9) // true
|
||||
maxHeap.has(obj9); // true
|
||||
|
||||
const peek9 = maxHeap.peek();
|
||||
console.log(peek9.keyA) // 'a9'
|
||||
console.log(peek9.keyA); // 'a9'
|
||||
|
||||
const heapToArr = maxHeap.toArray();
|
||||
console.log(heapToArr.map(ele => ele?.keyA)); // ['a9', 'a2', 'a6', 'a1', 'a0', 'a5']
|
||||
|
@ -449,7 +449,7 @@
|
|||
let i = 0;
|
||||
while (maxHeap.size > 0) {
|
||||
const polled = maxHeap.poll();
|
||||
console.log(polled.keyA) // values[i]
|
||||
console.log(polled.keyA); // values[i]
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue