diff --git a/README.md b/README.md
index 0ac942e..eb15c76 100644
--- a/README.md
+++ b/README.md
@@ -828,6 +828,7 @@ macOS Big Sur
Version 11.7.9
+***Our performance testing is conducted directly on the TypeScript source code. The actual performance of the compiled JavaScript code is generally 3 times higher. We have compared it with C++, and it is only 30% slower than C++.***
[//]: # (No deletion!!! Start of Replace Section)
diff --git a/package.json b/package.json
index 6fb1fc5..c6f5dfe 100644
--- a/package.json
+++ b/package.json
@@ -3,19 +3,19 @@
"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",
+ "module": "dist/esm/index.js",
"browser": "dist/umd/data-structure-typed.min.js",
- "types": "dist/mjs/index.d.ts",
+ "types": "dist/esm/index.d.ts",
"umd:main": "dist/umd/data-structure-typed.min.js",
"exports": {
".": {
- "import": "./dist/mjs/index.js",
+ "import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js"
}
},
"scripts": {
- "build": "npm run build:mjs && npm run build:cjs && npm run build:umd && npm run build:docs-class",
- "build:mjs": "rm -rf dist/mjs && tsc -p tsconfig-mjs.json",
+ "build": "npm run build:esm && npm run build:cjs && npm run build:umd && npm run build:docs-class",
+ "build:esm": "rm -rf dist/esm && tsc -p tsconfig-esm.json",
"build:cjs": "rm -rf dist/cjs && tsc -p tsconfig-cjs.json",
"build:umd": "tsup",
"build:docs": "npm run gen:examples && typedoc --out docs ./src",
@@ -24,7 +24,7 @@
"test:in-band": "jest --runInBand",
"test": "npm run test:in-band",
"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",
+ "test:perf": "npm run build:cjs && npm run build:esm && ts-node test/performance/reportor.ts",
"check": "tsc --noEmit",
"check:circular-refs": "dependency-cruiser src",
"lint:src": "eslint --fix 'src/**/*.{js,ts}'",
@@ -54,7 +54,7 @@
"url": "https://github.com/zrwusa/data-structure-typed/issues"
},
"homepage": "https://data-structure-typed-docs.vercel.app",
- "author": "Tyler Zeng
",
+ "author": "Pablo Zeng ",
"license": "MIT",
"publishConfig": {
"@zrwusa:registry": "https://npm.pkg.github.com"
diff --git a/src/data-structures/binary-tree/avl-tree-counter.ts b/src/data-structures/binary-tree/avl-tree-counter.ts
new file mode 100644
index 0000000..314d621
--- /dev/null
+++ b/src/data-structures/binary-tree/avl-tree-counter.ts
@@ -0,0 +1,463 @@
+/**
+ * data-structure-typed
+ *
+ * @author Pablo Zeng
+ * @copyright Copyright (c) 2022 Pablo Zeng
+ * @license MIT License
+ */
+import type {
+ AVLTreeCounterOptions,
+ BinaryTreeDeleteResult,
+ BSTNOptKeyOrNode,
+ BTNRep,
+ EntryCallback,
+ IterationType,
+ OptNodeOrNull
+} from '../../types';
+import { IBinaryTree } from '../../interfaces';
+import { AVLTree, AVLTreeNode } from './avl-tree';
+
+export class AVLTreeCounterNode extends AVLTreeNode {
+ /**
+ * 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
+ * of the binary tree node.
+ * @param {V} [value] - The `value` parameter is an optional parameter of type `V`. It represents the value of the binary
+ * tree node. If no value is provided, it will be `undefined`.
+ * @param {number} [count=1] - The `count` parameter is a number that represents the number of times a particular value
+ * occurs in a binary tree node. It has a default value of 1, which means that if no value is provided for the `count`
+ * parameter when creating a new instance of the `BinaryTreeNode` class.
+ */
+ constructor(key: K, value?: V, count = 1) {
+ super(key, value);
+ this.count = count;
+ }
+
+ override parent?: AVLTreeCounterNode = undefined;
+
+ override _left?: OptNodeOrNull> = undefined;
+
+ override get left(): OptNodeOrNull> {
+ return this._left;
+ }
+
+ override set left(v: OptNodeOrNull>) {
+ if (v) {
+ v.parent = this;
+ }
+ this._left = v;
+ }
+
+ override _right?: OptNodeOrNull> = undefined;
+
+ override get right(): OptNodeOrNull> {
+ return this._right;
+ }
+
+ override set right(v: OptNodeOrNull>) {
+ if (v) {
+ v.parent = this;
+ }
+ this._right = v;
+ }
+}
+
+/**
+ * The only distinction between a AVLTreeCounter and a AVLTree lies in the ability of the former to store duplicate nodes through the utilization of counters.
+ */
+export class AVLTreeCounter
+ extends AVLTree
+ implements IBinaryTree
+{
+ /**
+ * The constructor initializes a new AVLTreeCounter object with optional initial elements.
+ * @param keysNodesEntriesOrRaws - The `keysNodesEntriesOrRaws` parameter is an
+ * iterable object that can contain either keys, nodes, entries, or raw elements.
+ * @param [options] - The `options` parameter is an optional object that can be used to customize the
+ * behavior of the AVLTreeCounter. It can include properties such as `compareKeys` and
+ * `compareValues` functions to define custom comparison logic for keys and values, respectively.
+ */
+ constructor(
+ keysNodesEntriesOrRaws: Iterable> | R> = [],
+ options?: AVLTreeCounterOptions
+ ) {
+ super([], options);
+ if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);
+ }
+
+ protected _count = 0;
+
+ /**
+ * The function calculates the sum of the count property of all nodes in a tree using depth-first
+ * search.
+ * @returns the sum of the count property of all nodes in the tree.
+ */
+ get count(): number {
+ return this._count;
+ }
+
+ /**
+ * Time Complexity: O(n)
+ * Space Complexity: O(1)
+ *
+ * The function calculates the sum of the count property of all nodes in a tree using depth-first
+ * search.
+ * @returns the sum of the count property of all nodes in the tree.
+ */
+ getComputedCount(): number {
+ let sum = 0;
+ this.dfs(node => (sum += node.count));
+ return sum;
+ }
+
+ /**
+ * The function creates a new AVLTreeCounterNode with the specified key, value, and count.
+ * @param {K} key - The key parameter represents the key of the node being created. It is of type K,
+ * which is a generic type that can be replaced with any specific type when using the function.
+ * @param {V} [value] - The `value` parameter is an optional parameter that represents the value
+ * associated with the key in the node. It is of type `V`, which can be any data type.
+ * @param {number} [count] - The `count` parameter represents the number of occurrences of a
+ * key-value pair in the AVLTreeCounterNode. 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 AVLTreeCounterNode class, casted as AVLTreeCounterNode.
+ */
+ override createNode(key: K, value?: V, count?: number): AVLTreeCounterNode {
+ return new AVLTreeCounterNode(key, this._isMapMode ? undefined : value, count) as AVLTreeCounterNode;
+ }
+
+ /**
+ * The function creates a new AVLTreeCounter object with the specified options and returns it.
+ * @param [options] - The `options` parameter is an optional object that contains additional
+ * configuration options for creating the AVLTreeCounter. It can have the following properties:
+ * @returns a new instance of the AVLTreeCounter class, with the specified options, as a TREE
+ * object.
+ */
+ override createTree(options?: AVLTreeCounterOptions) {
+ return new AVLTreeCounter([], {
+ iterationType: this.iterationType,
+ isMapMode: this._isMapMode,
+ specifyComparable: this._specifyComparable,
+ toEntryFn: this._toEntryFn,
+ isReverse: this._isReverse,
+ ...options
+ });
+ }
+
+ /**
+ * The function checks if the input is an instance of AVLTreeCounterNode.
+ * @param {BTNRep>} keyNodeOrEntry - The parameter
+ * `keyNodeOrEntry` can be of type `R` or `BTNRep>`.
+ * @returns a boolean value indicating whether the input parameter `keyNodeOrEntry` is
+ * an instance of the `AVLTreeCounterNode` class.
+ */
+ override isNode(keyNodeOrEntry: BTNRep>): keyNodeOrEntry is AVLTreeCounterNode {
+ return keyNodeOrEntry instanceof AVLTreeCounterNode;
+ }
+
+ /**
+ * Time Complexity: O(log n)
+ * Space Complexity: O(1)
+ *
+ * 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>} keyNodeOrEntry - The
+ * `keyNodeOrEntry` parameter can accept a value of type `R`, which can be any type. It
+ * can also accept a value of type `BTNRep>`, 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.
+ * @param [count=1] - The `count` parameter represents the number of times the key-value pair should
+ * be added to the data structure. By default, it is set to 1, meaning that the key-value pair will
+ * be added once. However, you can specify a different value for `count` if you want to add
+ * @returns a boolean value.
+ */
+ override add(keyNodeOrEntry: BTNRep>, value?: V, count = 1): boolean {
+ const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value, count);
+ if (newNode === undefined) return false;
+
+ const orgNodeCount = newNode?.count || 0;
+ const inserted = super.add(newNode, newValue);
+ if (inserted) {
+ this._count += orgNodeCount;
+ }
+ return true;
+ }
+
+ /**
+ * Time Complexity: O(log n)
+ * Space Complexity: O(1)
+ *
+ * The function overrides the delete method in a binary tree data structure, handling deletion of
+ * nodes and maintaining balance in the tree.
+ * @param {BTNRep>} keyNodeOrEntry - 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.
+ * @param [ignoreCount=false] - The `ignoreCount` parameter in the `override delete` method is a
+ * boolean flag that determines whether to ignore the count of the node being deleted. If
+ * `ignoreCount` is set to `true`, the method will delete the node regardless of its count. If
+ * `ignoreCount` is set to
+ * @returns The `delete` method overrides the default delete behavior in a binary tree data
+ * structure. It takes a predicate or node to be deleted and an optional flag to ignore count. The
+ * method returns an array of `BinaryTreeDeleteResult` objects, each containing information about the
+ * deleted node and whether balancing is needed in the tree.
+ */
+ override delete(
+ keyNodeOrEntry: BTNRep>,
+ ignoreCount = false
+ ): BinaryTreeDeleteResult>[] {
+ const deletedResult: BinaryTreeDeleteResult>[] = [];
+ if (!this.root) return deletedResult;
+
+ const curr: AVLTreeCounterNode | undefined = this.getNode(keyNodeOrEntry) ?? undefined;
+ if (!curr) return deletedResult;
+
+ const parent: AVLTreeCounterNode | undefined = curr?.parent ? curr.parent : undefined;
+ let needBalanced: AVLTreeCounterNode | undefined = undefined,
+ orgCurrent: AVLTreeCounterNode | undefined = curr;
+
+ if (curr.count > 1 && !ignoreCount) {
+ curr.count--;
+ this._count--;
+ } else {
+ if (!curr.left) {
+ if (!parent) {
+ if (curr.right !== undefined && curr.right !== null) this._setRoot(curr.right);
+ } else {
+ const { familyPosition: fp } = curr;
+ if (fp === 'LEFT' || fp === 'ROOT_LEFT') {
+ parent.left = curr.right;
+ } else if (fp === 'RIGHT' || fp === 'ROOT_RIGHT') {
+ parent.right = curr.right;
+ }
+ needBalanced = parent;
+ }
+ } else {
+ const leftSubTreeRightMost = curr.left ? this.getRightMost(node => node, curr.left) : undefined;
+ if (leftSubTreeRightMost) {
+ const parentOfLeftSubTreeMax = leftSubTreeRightMost.parent;
+ orgCurrent = this._swapProperties(curr, leftSubTreeRightMost);
+ if (parentOfLeftSubTreeMax) {
+ if (parentOfLeftSubTreeMax.right === leftSubTreeRightMost) {
+ parentOfLeftSubTreeMax.right = leftSubTreeRightMost.left;
+ } else {
+ parentOfLeftSubTreeMax.left = leftSubTreeRightMost.left;
+ }
+ needBalanced = parentOfLeftSubTreeMax;
+ }
+ }
+ }
+ this._size = this._size - 1;
+ // TODO How to handle when the count of target node is lesser than current node's count
+ if (orgCurrent) this._count -= orgCurrent.count;
+ }
+
+ deletedResult.push({ deleted: orgCurrent, needBalanced });
+
+ if (needBalanced) {
+ this._balancePath(needBalanced);
+ }
+
+ return deletedResult;
+ }
+
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The "clear" function overrides the parent class's "clear" function and also resets the count to
+ * zero.
+ */
+ override clear() {
+ super.clear();
+ this._count = 0;
+ }
+
+ /**
+ * Time Complexity: O(n log n)
+ * Space Complexity: O(log n)
+ * The `perfectlyBalance` function takes a sorted array of nodes and builds a balanced binary search
+ * tree using either a recursive or iterative approach.
+ * @param {IterationType} iterationType - The `iterationType` parameter is an optional parameter that
+ * specifies the type of iteration to use when building the balanced binary search tree. It has a
+ * default value of `this.iterationType`, which means it will use the iteration type currently set in
+ * the object.
+ * @returns The function `perfectlyBalance` returns a boolean value. It returns `true` if the
+ * balancing operation is successful, and `false` if there are no nodes to balance.
+ */
+ override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {
+ const sorted = this.dfs(node => node, 'IN'),
+ n = sorted.length;
+ if (sorted.length < 1) return false;
+
+ this.clear();
+
+ if (iterationType === 'RECURSIVE') {
+ const buildBalanceBST = (l: number, r: number) => {
+ if (l > r) return;
+ const m = l + Math.floor((r - l) / 2);
+ const midNode = sorted[m];
+ if (this._isMapMode) this.add(midNode.key, undefined, midNode.count);
+ else this.add(midNode.key, midNode.value, midNode.count);
+ buildBalanceBST(l, m - 1);
+ buildBalanceBST(m + 1, r);
+ };
+
+ buildBalanceBST(0, n - 1);
+ return true;
+ } else {
+ const stack: [[number, number]] = [[0, n - 1]];
+ while (stack.length > 0) {
+ const popped = stack.pop();
+ if (popped) {
+ const [l, r] = popped;
+ if (l <= r) {
+ const m = l + Math.floor((r - l) / 2);
+ const midNode = sorted[m];
+ if (this._isMapMode) this.add(midNode.key, undefined, midNode.count);
+ else this.add(midNode.key, midNode.value, midNode.count);
+ stack.push([m + 1, r]);
+ stack.push([l, m - 1]);
+ }
+ }
+ }
+ return true;
+ }
+ }
+
+ /**
+ * Time complexity: O(n)
+ * Space complexity: O(n)
+ *
+ * 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() {
+ 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));
+ if (this._isMapMode) cloned._store = this._store;
+ return cloned;
+ }
+
+ /**
+ * The `map` function in TypeScript overrides the default behavior to create a new AVLTreeCounter
+ * with modified entries based on a provided callback.
+ * @param callback - The `callback` parameter is a function that will be called for each entry in the
+ * AVLTreeCounter. It takes four arguments:
+ * @param [options] - The `options` parameter in the `override map` function is of type
+ * `AVLTreeCounterOptions`. This parameter allows you to provide additional
+ * configuration options when creating a new `AVLTreeCounter` instance within the `map` function.
+ * These options
+ * @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 The `map` method is returning a new `AVLTreeCounter` instance with the entries
+ * transformed by the provided `callback` function. Each entry in the original tree is passed to the
+ * `callback` function along with the index and the original tree itself. The transformed entries are
+ * then added to the new `AVLTreeCounter` instance, which is returned at the end.
+ */
+ override map(
+ callback: EntryCallback,
+ options?: AVLTreeCounterOptions,
+ thisArg?: any
+ ): AVLTreeCounter {
+ const newTree = new AVLTreeCounter([], options);
+ let index = 0;
+ for (const [key, value] of this) {
+ newTree.add(callback.call(thisArg, key, value, index++, this));
+ }
+ return newTree;
+ }
+
+ /**
+ * The function `keyValueNodeEntryRawToNodeAndValue` converts a key, value, entry, or raw element into
+ * a node object.
+ * @param {BTNRep>} keyNodeOrEntry - The
+ * `keyNodeOrEntry` parameter can be of type `R` or `BTNRep>`.
+ * @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 AVLTreeCounterNode object or undefined.
+ */
+ protected override _keyValueNodeOrEntryToNodeAndValue(
+ keyNodeOrEntry: BTNRep>,
+ value?: V,
+ count = 1
+ ): [AVLTreeCounterNode | undefined, V | undefined] {
+ if (keyNodeOrEntry === undefined || keyNodeOrEntry === null) return [undefined, undefined];
+ if (this.isNode(keyNodeOrEntry)) return [keyNodeOrEntry, value];
+
+ if (this.isEntry(keyNodeOrEntry)) {
+ const [key, entryValue] = keyNodeOrEntry;
+ if (key === undefined || key === null) return [undefined, undefined];
+ const finalValue = value ?? entryValue;
+ return [this.createNode(key, finalValue, count), finalValue];
+ }
+
+ return [this.createNode(keyNodeOrEntry, value, count), value];
+ }
+
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The `_swapProperties` function swaps the properties (key, value, count, height) between two nodes
+ * in a binary search tree.
+ * @param {BSTNOptKeyOrNode>} srcNode - The `srcNode` parameter represents the source node
+ * that will be swapped with the `destNode`.
+ * @param {BSTNOptKeyOrNode>} 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: BSTNOptKeyOrNode>,
+ destNode: BSTNOptKeyOrNode>
+ ): AVLTreeCounterNode | undefined {
+ srcNode = this.ensureNode(srcNode);
+ destNode = this.ensureNode(destNode);
+ if (srcNode && destNode) {
+ const { key, value, count, height } = destNode;
+ const tempNode = this.createNode(key, value, count);
+ if (tempNode) {
+ tempNode.height = height;
+
+ destNode.key = srcNode.key;
+ if (!this._isMapMode) destNode.value = srcNode.value;
+ destNode.count = srcNode.count;
+ destNode.height = srcNode.height;
+
+ srcNode.key = tempNode.key;
+ if (!this._isMapMode) srcNode.value = tempNode.value;
+ srcNode.count = tempNode.count;
+ srcNode.height = tempNode.height;
+ }
+
+ 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 {AVLTreeCounterNode} oldNode - The oldNode parameter represents the node that needs to be replaced in the
+ * data structure. It is of type AVLTreeCounterNode.
+ * @param {AVLTreeCounterNode} newNode - The `newNode` parameter is an instance of the `AVLTreeCounterNode` class.
+ * @returns The method is returning the result of calling the `_replaceNode` method from the
+ * superclass, which is of type `AVLTreeCounterNode`.
+ */
+ protected override _replaceNode(
+ oldNode: AVLTreeCounterNode,
+ newNode: AVLTreeCounterNode
+ ): AVLTreeCounterNode {
+ newNode.count = oldNode.count + newNode.count;
+ return super._replaceNode(oldNode, newNode);
+ }
+}
diff --git a/src/data-structures/binary-tree/avl-tree-multi-map.ts b/src/data-structures/binary-tree/avl-tree-multi-map.ts
index 819d910..2d2119a 100644
--- a/src/data-structures/binary-tree/avl-tree-multi-map.ts
+++ b/src/data-structures/binary-tree/avl-tree-multi-map.ts
@@ -5,32 +5,21 @@
* @copyright Copyright (c) 2022 Pablo Zeng
* @license MIT License
*/
-import type {
- AVLTreeMultiMapOptions,
- BinaryTreeDeleteResult,
- BSTNOptKeyOrNode,
- BTNRep,
- EntryCallback,
- IterationType,
- OptNodeOrNull
-} from '../../types';
-import { IBinaryTree } from '../../interfaces';
+import { AVLTreeMultiMapOptions, BTNOptKeyOrNull, BTNRep, OptNodeOrNull } from '../../types';
import { AVLTree, AVLTreeNode } from './avl-tree';
-export class AVLTreeMultiMapNode extends AVLTreeNode {
+export class AVLTreeMultiMapNode extends AVLTreeNode {
/**
- * 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
- * of the binary tree node.
- * @param {V} [value] - The `value` parameter is an optional parameter of type `V`. It represents the value of the binary
- * tree node. If no value is provided, it will be `undefined`.
- * @param {number} [count=1] - The `count` parameter is a number that represents the number of times a particular value
- * occurs in a binary tree node. It has a default value of 1, which means that if no value is provided for the `count`
- * parameter when creating a new instance of the `BinaryTreeNode` class.
+ * This TypeScript constructor initializes an object with a key of type K and an array of values of
+ * type V.
+ * @param {K} key - The `key` parameter is typically used to store a unique identifier or key for the
+ * data being stored in the data structure. It helps in quickly accessing or retrieving the
+ * associated value in the data structure.
+ * @param {V[]} value - The `value` parameter in the constructor represents an array of values of
+ * type `V`.
*/
- constructor(key: K, value?: V, count = 1) {
+ constructor(key: K, value: V[]) {
super(key, value);
- this.count = count;
}
override parent?: AVLTreeMultiMapNode = undefined;
@@ -63,79 +52,52 @@ export class AVLTreeMultiMapNode extends AVLTreeNode {
}
/**
- * 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
- extends AVLTree
- implements IBinaryTree
-{
+export class AVLTreeMultiMap extends AVLTree<
+ K,
+ V[],
+ R,
+ MK,
+ MV,
+ MR
+> {
/**
- * The constructor initializes a new AVLTreeMultiMap object with optional initial elements.
- * @param keysNodesEntriesOrRaws - The `keysNodesEntriesOrRaws` parameter is an
- * iterable object that can contain either keys, nodes, entries, or raw elements.
- * @param [options] - The `options` parameter is an optional object that can be used to customize the
- * behavior of the AVLTreeMultiMap. It can include properties such as `compareKeys` and
- * `compareValues` functions to define custom comparison logic for keys and values, respectively.
+ * The constructor initializes an AVLTreeMultiMap with the provided keys, nodes, entries, or raw data
+ * and options.
+ * @param keysNodesEntriesOrRaws - The `keysNodesEntriesOrRaws` parameter in the constructor is an
+ * iterable that can contain either key-value pairs represented as `BTNRep>` or raw data represented as `R`. This parameter is used to initialize
+ * the AVLTreeMulti
+ * @param [options] - The `options` parameter in the constructor is of type
+ * `AVLTreeMultiMapOptions`. It is an optional parameter that allows you to specify
+ * additional options for configuring the AVLTreeMultiMap instance.
*/
constructor(
- keysNodesEntriesOrRaws: Iterable>> = [],
- options?: AVLTreeMultiMapOptions
+ keysNodesEntriesOrRaws: Iterable> | R> = [],
+ options?: AVLTreeMultiMapOptions
) {
- super([], options);
- if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);
- }
-
- protected _count = 0;
-
- /**
- * The function calculates the sum of the count property of all nodes in a tree using depth-first
- * search.
- * @returns the sum of the count property of all nodes in the tree.
- */
- get count(): number {
- return this._count;
+ super([], { ...options, isMapMode: true });
+ if (keysNodesEntriesOrRaws) {
+ this.addMany(keysNodesEntriesOrRaws);
+ }
}
/**
- * Time Complexity: O(n)
+ * Time Complexity: O(1)
* Space Complexity: O(1)
*
- * The function calculates the sum of the count property of all nodes in a tree using depth-first
- * search.
- * @returns the sum of the count property of all nodes in the tree.
+ * The function `createTree` in TypeScript overrides the creation of an AVLTreeMultiMap with
+ * specified options.
+ * @param [options] - The `options` parameter in the `createTree` function is of type
+ * `AVLTreeMultiMapOptions`. This means it is an object that can have properties of type
+ * `K`, `V[]`, and `R`. The function creates a new `AVL
+ * @returns The `createTree` method is returning a new instance of `AVLTreeMultiMap` with the
+ * provided options.
*/
- getComputedCount(): number {
- let sum = 0;
- this.dfs(node => (sum += node.count));
- return sum;
- }
-
- /**
- * The function creates a new AVLTreeMultiMapNode with the specified key, value, and count.
- * @param {K} key - The key parameter represents the key of the node being created. It is of type K,
- * which is a generic type that can be replaced with any specific type when using the function.
- * @param {V} [value] - The `value` parameter is an optional parameter that represents the value
- * associated with the key in the node. It is of type `V`, which can be any data type.
- * @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 AVLTreeMultiMapNode.
- */
- override createNode(key: K, value?: V, count?: number): AVLTreeMultiMapNode {
- return new AVLTreeMultiMapNode(key, this._isMapMode ? undefined : value, count) as AVLTreeMultiMapNode;
- }
-
- /**
- * The function creates a new AVLTreeMultiMap object with the specified options and returns it.
- * @param [options] - The `options` parameter is an optional object that contains additional
- * configuration options for creating the AVLTreeMultiMap. It can have the following properties:
- * @returns a new instance of the AVLTreeMultiMap class, with the specified options, as a TREE
- * object.
- */
- override createTree(options?: AVLTreeMultiMapOptions) {
+ override createTree(options?: AVLTreeMultiMapOptions) {
return new AVLTreeMultiMap([], {
iterationType: this.iterationType,
- isMapMode: this._isMapMode,
specifyComparable: this._specifyComparable,
toEntryFn: this._toEntryFn,
isReverse: this._isReverse,
@@ -143,331 +105,121 @@ export class AVLTreeMultiMap> | R} keyNodeEntryOrRaw - The parameter
- * `keyNodeEntryOrRaw` can be of type `R` or `BTNRep>`.
- * @returns a boolean value indicating whether the input parameter `keyNodeEntryOrRaw` is
- * an instance of the `AVLTreeMultiMapNode` class.
- */
- override isNode(
- keyNodeEntryOrRaw: BTNRep> | R
- ): keyNodeEntryOrRaw is AVLTreeMultiMapNode {
- return keyNodeEntryOrRaw instanceof AVLTreeMultiMapNode;
- }
-
- /**
- * Time Complexity: O(log n)
- * Space Complexity: O(1)
- *
- * 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> | 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>`, 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.
- * @param [count=1] - The `count` parameter represents the number of times the key-value pair should
- * be added to the data structure. By default, it is set to 1, meaning that the key-value pair will
- * 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> | R, value?: V, count = 1): boolean {
- const [newNode, newValue] = this._keyValueNodeEntryRawToNodeAndValue(keyNodeEntryOrRaw, value, count);
- if (newNode === undefined) return false;
-
- const orgNodeCount = newNode?.count || 0;
- const inserted = super.add(newNode, newValue);
- if (inserted) {
- this._count += orgNodeCount;
- }
- return true;
- }
-
- /**
- * Time Complexity: O(log n)
- * Space Complexity: O(1)
- *
- * The function overrides the delete method in a binary tree data structure, handling deletion of
- * nodes and maintaining balance in the tree.
- * @param {BTNRep> | 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.
- * @param [ignoreCount=false] - The `ignoreCount` parameter in the `override delete` method is a
- * boolean flag that determines whether to ignore the count of the node being deleted. If
- * `ignoreCount` is set to `true`, the method will delete the node regardless of its count. If
- * `ignoreCount` is set to
- * @returns The `delete` method overrides the default delete behavior in a binary tree data
- * structure. It takes a predicate or node to be deleted and an optional flag to ignore count. The
- * 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> | R,
- ignoreCount = false
- ): BinaryTreeDeleteResult>[] {
- const deletedResult: BinaryTreeDeleteResult>[] = [];
- if (!this.root) return deletedResult;
-
- const curr: AVLTreeMultiMapNode | undefined = this.getNode(keyNodeEntryOrRaw) ?? undefined;
- if (!curr) return deletedResult;
-
- const parent: AVLTreeMultiMapNode | undefined = curr?.parent ? curr.parent : undefined;
- let needBalanced: AVLTreeMultiMapNode | undefined = undefined,
- orgCurrent: AVLTreeMultiMapNode | undefined = curr;
-
- if (curr.count > 1 && !ignoreCount) {
- curr.count--;
- this._count--;
- } else {
- if (!curr.left) {
- if (!parent) {
- if (curr.right !== undefined && curr.right !== null) this._setRoot(curr.right);
- } else {
- const { familyPosition: fp } = curr;
- if (fp === 'LEFT' || fp === 'ROOT_LEFT') {
- parent.left = curr.right;
- } else if (fp === 'RIGHT' || fp === 'ROOT_RIGHT') {
- parent.right = curr.right;
- }
- needBalanced = parent;
- }
- } else {
- const leftSubTreeRightMost = curr.left ? this.getRightMost(node => node, curr.left) : undefined;
- if (leftSubTreeRightMost) {
- const parentOfLeftSubTreeMax = leftSubTreeRightMost.parent;
- orgCurrent = this._swapProperties(curr, leftSubTreeRightMost);
- if (parentOfLeftSubTreeMax) {
- if (parentOfLeftSubTreeMax.right === leftSubTreeRightMost) {
- parentOfLeftSubTreeMax.right = leftSubTreeRightMost.left;
- } else {
- parentOfLeftSubTreeMax.left = leftSubTreeRightMost.left;
- }
- needBalanced = parentOfLeftSubTreeMax;
- }
- }
- }
- this._size = this._size - 1;
- // TODO How to handle when the count of target node is lesser than current node's count
- if (orgCurrent) this._count -= orgCurrent.count;
- }
-
- deletedResult.push({ deleted: orgCurrent, needBalanced });
-
- if (needBalanced) {
- this._balancePath(needBalanced);
- }
-
- return deletedResult;
- }
-
/**
* Time Complexity: O(1)
* Space Complexity: O(1)
*
- * The "clear" function overrides the parent class's "clear" function and also resets the count to
- * zero.
+ * The function `createNode` overrides the method to create a new AVLTreeMultiMapNode with a
+ * specified key and an empty array of values.
+ * @param {K} key - The `key` parameter in the `createNode` method represents the key of the node
+ * that will be created in the AVLTreeMultiMap.
+ * @returns An AVLTreeMultiMapNode object is being returned, initialized with the provided key and an
+ * empty array.
*/
- override clear() {
- super.clear();
- this._count = 0;
+ override createNode(key: K): AVLTreeMultiMapNode {
+ return new AVLTreeMultiMapNode(key, []);
+ }
+
+ override add(node: BTNRep>): boolean;
+
+ override add(key: K, value: V): boolean;
+
+ /**
+ * Time Complexity: O(log n)
+ * Space Complexity: O(log n)
+ *
+ * The function `add` in TypeScript overrides the superclass method to add key-value pairs to an AVL
+ * tree multi-map.
+ * @param {BTNRep> | K} keyNodeOrEntry - The `keyNodeOrEntry`
+ * parameter in the `override add` method can be either a key-value pair entry or just a key. If it
+ * is a key-value pair entry, it will be in the format `[key, values]`, where `key` is the key and
+ * `values`
+ * @param {V} [value] - The `value` parameter in the `override add` method represents the value that
+ * you want to add to the AVLTreeMultiMap. It can be a single value or an array of values associated
+ * with a specific key.
+ * @returns The `override add` method is returning a boolean value, which indicates whether the
+ * addition operation was successful or not.
+ */
+ override add(keyNodeOrEntry: BTNRep> | K, value?: V): boolean {
+ if (this.isRealNode(keyNodeOrEntry)) return super.add(keyNodeOrEntry);
+
+ const _commonAdd = (key?: BTNOptKeyOrNull, values?: V[]) => {
+ if (key === undefined || key === null) return false;
+
+ const existingValues = this.get(key);
+ if (existingValues !== undefined && values !== undefined) {
+ for (const value of values) existingValues.push(value);
+ return true;
+ }
+
+ const existingNode = this.getNode(key);
+ if (this.isRealNode(existingNode)) {
+ if (existingValues === undefined) {
+ super.add(key, values);
+ return true;
+ }
+ if (values !== undefined) {
+ for (const value of values) existingValues.push(value);
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return super.add(key, values);
+ }
+ };
+
+ if (this.isEntry(keyNodeOrEntry)) {
+ const [key, values] = keyNodeOrEntry;
+ return _commonAdd(key, value !== undefined ? [value] : values);
+ }
+
+ return _commonAdd(keyNodeOrEntry, value !== undefined ? [value] : undefined);
}
/**
- * Time Complexity: O(n log n)
+ * Time Complexity: O(log n)
* Space Complexity: O(log n)
- * The `perfectlyBalance` function takes a sorted array of nodes and builds a balanced binary search
- * tree using either a recursive or iterative approach.
- * @param {IterationType} iterationType - The `iterationType` parameter is an optional parameter that
- * specifies the type of iteration to use when building the balanced binary search tree. It has a
- * default value of `this.iterationType`, which means it will use the iteration type currently set in
- * the object.
- * @returns The function `perfectlyBalance` returns a boolean value. It returns `true` if the
- * balancing operation is successful, and `false` if there are no nodes to balance.
+ *
+ * The function `deleteValue` removes a specific value from a key in an AVLTreeMultiMap data
+ * structure and deletes the entire node if no values are left for that key.
+ * @param {BTNRep> | K} keyNodeOrEntry - The `keyNodeOrEntry`
+ * parameter in the `deleteValue` function can be either a `BTNRep` object representing a key-value
+ * pair in the AVLTreeMultiMapNode, or just the key itself.
+ * @param {V} value - The `value` parameter in the `deleteValue` function represents the specific
+ * value that you want to delete from the multi-map data structure associated with a particular key.
+ * The function checks if the value exists in the array of values associated with the key, and if
+ * found, removes it from the array.
+ * @returns The `deleteValue` function returns a boolean value. It returns `true` if the specified
+ * `value` was successfully deleted from the array of values associated with the `keyNodeOrEntry`. If
+ * the value was not found in the array, it returns `false`.
*/
- override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {
- const sorted = this.dfs(node => node, 'IN'),
- n = sorted.length;
- if (sorted.length < 1) return false;
+ deleteValue(keyNodeOrEntry: BTNRep> | K, value: V): boolean {
+ const values = this.get(keyNodeOrEntry);
+ if (Array.isArray(values)) {
+ const index = values.indexOf(value);
+ if (index === -1) return false;
+ values.splice(index, 1);
- this.clear();
+ // If no values left, remove the entire node
+ if (values.length === 0) this.delete(keyNodeOrEntry);
- if (iterationType === 'RECURSIVE') {
- const buildBalanceBST = (l: number, r: number) => {
- if (l > r) return;
- const m = l + Math.floor((r - l) / 2);
- const midNode = sorted[m];
- if (this._isMapMode) this.add(midNode.key, undefined, midNode.count);
- else this.add(midNode.key, midNode.value, midNode.count);
- buildBalanceBST(l, m - 1);
- buildBalanceBST(m + 1, r);
- };
-
- buildBalanceBST(0, n - 1);
- return true;
- } else {
- const stack: [[number, number]] = [[0, n - 1]];
- while (stack.length > 0) {
- const popped = stack.pop();
- if (popped) {
- const [l, r] = popped;
- if (l <= r) {
- const m = l + Math.floor((r - l) / 2);
- const midNode = sorted[m];
- if (this._isMapMode) this.add(midNode.key, undefined, midNode.count);
- else this.add(midNode.key, midNode.value, midNode.count);
- stack.push([m + 1, r]);
- stack.push([l, m - 1]);
- }
- }
- }
return true;
}
+ return false;
}
/**
- * Time complexity: O(n)
- * Space complexity: O(n)
+ * Time Complexity: O(n)
+ * Space Complexity: O(n)
*
- * 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.
+ * The function `clone` overrides the default cloning behavior to create a deep copy of a tree
+ * structure.
+ * @returns A cloned tree object is being returned.
*/
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));
- if (this._isMapMode) cloned._store = this._store;
+ this._clone(cloned);
return cloned;
}
-
- /**
- * The `map` function in TypeScript overrides the default behavior to create a new AVLTreeMultiMap
- * with modified entries based on a provided callback.
- * @param callback - The `callback` parameter is a function that will be called for each entry in the
- * AVLTreeMultiMap. It takes four arguments:
- * @param [options] - The `options` parameter in the `override map` function is of type
- * `AVLTreeMultiMapOptions`. This parameter allows you to provide additional
- * configuration options when creating a new `AVLTreeMultiMap` instance within the `map` function.
- * These options
- * @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 The `map` method is returning a new `AVLTreeMultiMap` instance with the entries
- * transformed by the provided `callback` function. Each entry in the original tree is passed to the
- * `callback` function along with the index and the original tree itself. The transformed entries are
- * then added to the new `AVLTreeMultiMap` instance, which is returned at the end.
- */
- override map(
- callback: EntryCallback,
- options?: AVLTreeMultiMapOptions,
- thisArg?: any
- ): AVLTreeMultiMap {
- const newTree = new AVLTreeMultiMap([], options);
- let index = 0;
- for (const [key, value] of this) {
- newTree.add(callback.call(thisArg, key, value, index++, this));
- }
- return newTree;
- }
-
- /**
- * The function `keyValueNodeEntryRawToNodeAndValue` converts a key, value, entry, or raw element into
- * a node object.
- * @param {BTNRep> | R} keyNodeEntryOrRaw - The
- * `keyNodeEntryOrRaw` parameter can be of type `R` or `BTNRep>`.
- * @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 AVLTreeMultiMapNode object or undefined.
- */
- protected override _keyValueNodeEntryRawToNodeAndValue(
- keyNodeEntryOrRaw: BTNRep> | R,
- value?: V,
- count = 1
- ): [AVLTreeMultiMapNode | 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;
- return [this.createNode(key, finalValue, 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, count), finalValue];
- }
-
- if (this.isKey(keyNodeEntryOrRaw)) return [this.createNode(keyNodeEntryOrRaw, value, count), value];
-
- return [undefined, undefined];
- }
-
- /**
- * Time Complexity: O(1)
- * Space Complexity: O(1)
- *
- * The `_swapProperties` function swaps the properties (key, value, count, height) between two nodes
- * in a binary search tree.
- * @param {R | BSTNOptKeyOrNode>} srcNode - The `srcNode` parameter represents the source node
- * that will be swapped with the `destNode`.
- * @param {R | BSTNOptKeyOrNode>} 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>,
- destNode: R | BSTNOptKeyOrNode>
- ): AVLTreeMultiMapNode | undefined {
- srcNode = this.ensureNode(srcNode);
- destNode = this.ensureNode(destNode);
- if (srcNode && destNode) {
- const { key, value, count, height } = destNode;
- const tempNode = this.createNode(key, value, count);
- if (tempNode) {
- tempNode.height = height;
-
- destNode.key = srcNode.key;
- if (!this._isMapMode) destNode.value = srcNode.value;
- destNode.count = srcNode.count;
- destNode.height = srcNode.height;
-
- srcNode.key = tempNode.key;
- if (!this._isMapMode) srcNode.value = tempNode.value;
- srcNode.count = tempNode.count;
- srcNode.height = tempNode.height;
- }
-
- 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 {AVLTreeMultiMapNode} oldNode - The oldNode parameter represents the node that needs to be replaced in the
- * data structure. It is of type AVLTreeMultiMapNode.
- * @param {AVLTreeMultiMapNode} newNode - The `newNode` parameter is an instance of the `AVLTreeMultiMapNode` class.
- * @returns The method is returning the result of calling the `_replaceNode` method from the
- * superclass, which is of type `AVLTreeMultiMapNode`.
- */
- protected override _replaceNode(
- oldNode: AVLTreeMultiMapNode,
- newNode: AVLTreeMultiMapNode
- ): AVLTreeMultiMapNode {
- newNode.count = oldNode.count + newNode.count;
- return super._replaceNode(oldNode, newNode);
- }
}
diff --git a/src/data-structures/binary-tree/avl-tree.ts b/src/data-structures/binary-tree/avl-tree.ts
index 87a56a0..741edfc 100644
--- a/src/data-structures/binary-tree/avl-tree.ts
+++ b/src/data-structures/binary-tree/avl-tree.ts
@@ -18,12 +18,13 @@ import { IBinaryTree } from '../../interfaces';
export class AVLTreeNode extends BSTNode {
/**
- * The constructor function initializes a new instance of a class with a key and an optional value,
- * and sets the height property to 0.
- * @param {K} key - The "key" parameter is of type K, which represents the type of the key for the
- * constructor. It is used to initialize the key property of the object 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 constructor.
+ * This TypeScript constructor function initializes an instance with a key and an optional value.
+ * @param {K} key - The `key` parameter is typically used to uniquely identify an object or element
+ * within a data structure. It serves as a reference or identifier for accessing or manipulating the
+ * associated value or data.
+ * @param {V} [value] - The `value` parameter in the constructor is optional, meaning it does not
+ * have to be provided when creating an instance of the class. If a value is not provided, it will
+ * default to `undefined`.
*/
constructor(key: K, value?: V) {
super(key, value);
@@ -72,18 +73,18 @@ export class AVLTree
{
/**
- * This is a constructor function for an AVLTree class that initializes the tree with keys, nodes,
- * entries, or raw elements.
- * @param keysNodesEntriesOrRaws - The `keysNodesEntriesOrRaws` parameter is an
- * iterable object that can contain either keys, nodes, entries, or raw elements. These elements will
- * be used to initialize the AVLTree.
- * @param [options] - The `options` parameter is an optional object that can be used to customize the
- * behavior of the AVLTree. It can include properties such as `compareFn` (a function used to compare
- * keys), `allowDuplicates` (a boolean indicating whether duplicate keys are allowed), and
- * `nodeBuilder` (
+ * This TypeScript constructor initializes an AVLTree with keys, nodes, entries, or raw data provided
+ * in an iterable format.
+ * @param keysNodesEntriesOrRaws - The `keysNodesEntriesOrRaws` parameter in the constructor is an
+ * iterable that can contain either `BTNRep>` objects or `R` objects. It is
+ * used to initialize the AVLTree with key-value pairs or raw data entries. If provided
+ * @param [options] - The `options` parameter in the constructor is of type `AVLTreeOptions`. It is an optional parameter that allows you to specify additional options for configuring the
+ * AVL tree. These options could include things like custom comparators, initial capacity, or any
+ * other configuration settings specific
*/
constructor(
- keysNodesEntriesOrRaws: Iterable>> = [],
+ keysNodesEntriesOrRaws: Iterable> | R> = [],
options?: AVLTreeOptions
) {
super([], options);
@@ -91,6 +92,9 @@ export class AVLTree> | R} keyNodeEntryOrRaw - The parameter
- * `keyNodeEntryOrRaw` can be of type `R` or `BTNRep>`.
- * @returns a boolean value indicating whether the input parameter `keyNodeEntryOrRaw` is
+ * @param {BTNRep>} keyNodeOrEntry - The parameter
+ * `keyNodeOrEntry` can be of type `R` or `BTNRep>`.
+ * @returns a boolean value indicating whether the input parameter `keyNodeOrEntry` is
* an instance of the `AVLTreeNode` class.
*/
- override isNode(keyNodeEntryOrRaw: BTNRep> | R): keyNodeEntryOrRaw is AVLTreeNode {
- return keyNodeEntryOrRaw instanceof AVLTreeNode;
+ override isNode(keyNodeOrEntry: BTNRep>): keyNodeOrEntry is AVLTreeNode {
+ return keyNodeOrEntry instanceof AVLTreeNode;
}
/**
* Time Complexity: O(log n)
- * Space Complexity: O(1)
+ * Space Complexity: O(log n)
*
* 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> | R} keyNodeEntryOrRaw - The parameter
- * `keyNodeEntryOrRaw` can accept values of type `R`, `BTNRep>`, or
- * `RawElement`.
+ * @param {BTNRep>} keyNodeOrEntry - The parameter
+ * `keyNodeOrEntry` can accept values of type `R`, `BTNRep>`
* @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> | R, value?: V): boolean {
- if (keyNodeEntryOrRaw === null) return false;
- const inserted = super.add(keyNodeEntryOrRaw, value);
- if (inserted) this._balancePath(keyNodeEntryOrRaw);
+ override add(keyNodeOrEntry: BTNRep>, value?: V): boolean {
+ if (keyNodeOrEntry === null) return false;
+ const inserted = super.add(keyNodeOrEntry, value);
+ if (inserted) this._balancePath(keyNodeOrEntry);
return inserted;
}
/**
* Time Complexity: O(log n)
- * Space Complexity: O(1)
+ * Space Complexity: O(log n)
*
* The function overrides the delete method in a TypeScript class, performs deletion, and then
* balances the tree if necessary.
- * @param {BTNRep> | R} keyNodeEntryOrRaw - The `keyNodeEntryOrRaw`
+ * @param {BTNRep>} keyNodeOrEntry - The `keyNodeOrEntry`
* 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> | R): BinaryTreeDeleteResult>[] {
- const deletedResults = super.delete(keyNodeEntryOrRaw);
+ override delete(keyNodeOrEntry: BTNRep>): BinaryTreeDeleteResult>[] {
+ const deletedResults = super.delete(keyNodeOrEntry);
for (const { needBalanced } of deletedResults) {
if (needBalanced) {
this._balancePath(needBalanced);
@@ -175,6 +184,26 @@ export class AVLTree`. It is an optional parameter that allows you to specify additional
+ * options for the AVL tree being created during the mapping process. These options could include
+ * custom comparators, initial
+ * @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`) within the callback function. This can be useful when you want to access
+ * properties or
+ * @returns The `map` method is returning a new AVLTree instance (`newTree`) with the entries
+ * modified by the provided callback function.
+ */
override map(
callback: EntryCallback,
options?: AVLTreeOptions,
@@ -188,6 +217,14 @@ export class AVLTree>} srcNode - The `srcNode` parameter represents either a node
+ * @param {BSTNOptKeyOrNode>} srcNode - The `srcNode` parameter represents either a node
* object (`AVLTreeNode`) or a key-value pair (`R`) that is being swapped with another node.
- * @param {R | BSTNOptKeyOrNode>} destNode - The `destNode` parameter is either an instance of
+ * @param {BSTNOptKeyOrNode>} destNode - The `destNode` parameter is either an instance of
* `R` or an instance of `BSTNOptKeyOrNode>`.
* @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>,
- destNode: R | BSTNOptKeyOrNode>
+ srcNode: BSTNOptKeyOrNode>,
+ destNode: BSTNOptKeyOrNode>
): AVLTreeNode | undefined {
const srcNodeEnsured = this.ensureNode(srcNode);
const destNodeEnsured = this.ensureNode(destNode);
@@ -450,10 +487,10 @@ export class AVLTree> | R} node - The `node` parameter can be of type `R` or
+ * @param {BTNRep>} node - The `node` parameter can be of type `R` or
* `BTNRep>`.
*/
- protected _balancePath(node: BTNRep> | R): void {
+ protected _balancePath(node: BTNRep>): 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++) {
diff --git a/src/data-structures/binary-tree/binary-indexed-tree.ts b/src/data-structures/binary-tree/binary-indexed-tree.ts
index ce722c8..aaa6694 100644
--- a/src/data-structures/binary-tree/binary-indexed-tree.ts
+++ b/src/data-structures/binary-tree/binary-indexed-tree.ts
@@ -7,6 +7,9 @@
*/
import { getMSB } from '../../utils';
+/**
+ *
+ */
export class BinaryIndexedTree {
protected readonly _freq: number;
protected readonly _max: number;
diff --git a/src/data-structures/binary-tree/binary-tree.ts b/src/data-structures/binary-tree/binary-tree.ts
index a175e84..892d434 100644
--- a/src/data-structures/binary-tree/binary-tree.ts
+++ b/src/data-structures/binary-tree/binary-tree.ts
@@ -36,6 +36,14 @@ import { DFSOperation, Range } from '../../common';
* @template BinaryTreeNode - The type of the family relationship in the binary tree.
*/
export class BinaryTreeNode {
+ /**
+ * The constructor function initializes an object with a key and an optional value in TypeScript.
+ * @param {K} key - The `key` parameter in the constructor function is used to store the key value
+ * for the key-value pair.
+ * @param {V} [value] - The `value` parameter in the constructor is optional, meaning it does not
+ * have to be provided when creating an instance of the class. If a `value` is not provided, it will
+ * default to `undefined`.
+ */
constructor(key: K, value?: V) {
this.key = key;
this.value = value;
@@ -129,16 +137,14 @@ export class BinaryTree
implements IBinaryTree
{
- iterationType: IterationType = 'ITERATIVE';
-
/**
- * The constructor initializes a binary tree with optional options and adds keys, nodes, entries, or
- * raw data if provided.
- * @param keysNodesEntriesOrRaws - The `keysNodesEntriesOrRaws` parameter in the constructor
- * is an iterable that can contain elements of type `BTNRep>` or `R`. It is
- * initialized with an empty array `[]` by default.
- * @param [options] - The `options` parameter in the constructor is an object that can contain the
- * following properties:
+ * This TypeScript constructor function initializes a binary tree with optional options and adds
+ * elements based on the provided input.
+ * @param keysNodesEntriesOrRaws - The `keysNodesEntriesOrRaws` parameter in the constructor is an
+ * iterable that can contain either objects of type `BTNRep>` or `R`. It
+ * is used to initialize the binary tree with keys, nodes, entries, or raw data.
+ * @param [options] - The `options` parameter in the constructor is an optional object that can
+ * contain the following properties:
*/
constructor(
keysNodesEntriesOrRaws: Iterable> | R> = [],
@@ -156,6 +162,8 @@ export class BinaryTree.
*/
createNode(key: K, value?: V): BinaryTreeNode {
- return new BinaryTreeNode(key, this._isMapMode ? undefined : value) as BinaryTreeNode;
+ return new BinaryTreeNode(key, this._isMapMode ? undefined : value);
}
/**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
* The function creates a binary tree with the specified options.
* @param [options] - The `options` parameter in the `createTree` function is an optional parameter
* that allows you to provide partial configuration options for creating a binary tree. It is of type
@@ -231,7 +242,7 @@ export class BinaryTree> | R} keyNodeEntryOrRaw - The `keyNodeEntryOrRaw`
+ * @param {BTNRep>} keyNodeOrEntry - The `keyNodeOrEntry`
* parameter in the `ensureNode` function can be of type `BTNRep>` or `R`. It
* is used to determine whether the input is a key, node, entry, or raw data. The
* @param {IterationType} iterationType - The `iterationType` parameter in the `ensureNode` function
@@ -241,48 +252,49 @@ export class BinaryTree> | R,
+ keyNodeOrEntry: BTNRep>,
iterationType: IterationType = this.iterationType
): OptNodeOrNull> {
- if (keyNodeEntryOrRaw === null) return null;
- if (keyNodeEntryOrRaw === undefined) return;
- if (keyNodeEntryOrRaw === this._NIL) return;
- if (this.isNode(keyNodeEntryOrRaw)) return keyNodeEntryOrRaw;
+ if (keyNodeOrEntry === null) return null;
+ if (keyNodeOrEntry === undefined) return;
+ if (keyNodeOrEntry === this._NIL) return;
- if (this.isEntry(keyNodeEntryOrRaw)) {
- const key = keyNodeEntryOrRaw[0];
+ if (this.isNode(keyNodeOrEntry)) return keyNodeOrEntry;
+
+ if (this.isEntry(keyNodeOrEntry)) {
+ const key = keyNodeOrEntry[0];
if (key === null) return null;
if (key === undefined) return;
return this.getNode(key, this._root, iterationType);
}
- if (this._toEntryFn) {
- const [key] = this._toEntryFn(keyNodeEntryOrRaw as R);
- if (this.isKey(key)) return this.getNode(key);
- }
-
- if (this.isKey(keyNodeEntryOrRaw)) return this.getNode(keyNodeEntryOrRaw, this._root, iterationType);
- return;
+ return this.getNode(keyNodeOrEntry, this._root, iterationType);
}
/**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
* The function isNode checks if the input is an instance of BinaryTreeNode.
- * @param {BTNRep> | R} keyNodeEntryOrRaw - The parameter
- * `keyNodeEntryOrRaw` can be either a key, a node, an entry, or raw data. The function is
+ * @param {BTNRep>} keyNodeOrEntry - The parameter
+ * `keyNodeOrEntry` can be either a key, a node, an entry, or raw data. The function is
* checking if the input is an instance of a `BinaryTreeNode` and returning a boolean value
* accordingly.
- * @returns The function `isNode` is checking if the input `keyNodeEntryOrRaw` is an instance of
+ * @returns The function `isNode` is checking if the input `keyNodeOrEntry` is an instance of
* `BinaryTreeNode`. If it is, the function returns `true`, indicating that the input is a node. If
* it is not an instance of `BinaryTreeNode`, the function returns `false`, indicating that the input
* is not a node.
*/
- isNode(keyNodeEntryOrRaw: BTNRep> | R): keyNodeEntryOrRaw is BinaryTreeNode {
- return keyNodeEntryOrRaw instanceof BinaryTreeNode;
+ isNode(keyNodeOrEntry: BTNRep>): keyNodeOrEntry is BinaryTreeNode {
+ return keyNodeOrEntry instanceof BinaryTreeNode;
}
/**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
* The function `isRaw` checks if the input parameter is of type `R` by verifying if it is an object.
- * @param {BTNRep> | R} keyNodeEntryOrRaw - BTNRep> | R
+ * @param {BTNRep> | R} keyNodeEntryOrRaw - BTNRep>
* @returns The function `isRaw` is checking if the `keyNodeEntryOrRaw` parameter is of type `R` by
* checking if it is an object. If the parameter is an object, the function will return `true`,
* indicating that it is of type `R`.
@@ -292,95 +304,122 @@ export class BinaryTree> | R} keyNodeEntryOrRaw - The `keyNodeEntryOrRaw`
+ * @param {BTNRep>} keyNodeOrEntry - The `keyNodeOrEntry`
* parameter in the `isRealNode` function can be of type `BTNRep>` or `R`.
* The function checks if the input parameter is a `BinaryTreeNode` type by verifying if it is not equal
- * @returns The function `isRealNode` is checking if the input `keyNodeEntryOrRaw` is a valid
+ * @returns The function `isRealNode` is checking if the input `keyNodeOrEntry` is a valid
* node by comparing it to `this._NIL`, `null`, and `undefined`. If the input is not one of these
* values, it then calls the `isNode` method to further determine if the input is a node. The
* function will return a boolean value indicating whether the
*/
- isRealNode(keyNodeEntryOrRaw: BTNRep> | R): keyNodeEntryOrRaw is BinaryTreeNode {
- if (keyNodeEntryOrRaw === this._NIL || keyNodeEntryOrRaw === null || keyNodeEntryOrRaw === undefined) return false;
- return this.isNode(keyNodeEntryOrRaw);
+ isRealNode(keyNodeOrEntry: BTNRep>): keyNodeOrEntry is BinaryTreeNode {
+ if (keyNodeOrEntry === this._NIL || keyNodeOrEntry === null || keyNodeOrEntry === undefined) return false;
+ return this.isNode(keyNodeOrEntry);
}
/**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
* The function checks if a given input is a valid node or null.
- * @param {BTNRep> | R} keyNodeEntryOrRaw - The parameter
- * `keyNodeEntryOrRaw` in the `isRealNodeOrNull` function can be of type `BTNRep>} keyNodeOrEntry - The parameter
+ * `keyNodeOrEntry` in the `isRealNodeOrNull` function can be of type `BTNRep>` or `R`. It is a union type that can either be a key, a node, an entry, or
* @returns The function `isRealNodeOrNull` is returning a boolean value. It checks if the input
- * `keyNodeEntryOrRaw` is either `null` or a real node, and returns `true` if it is a node or
+ * `keyNodeOrEntry` is either `null` or a real node, and returns `true` if it is a node or
* `null`, and `false` otherwise.
*/
- isRealNodeOrNull(
- keyNodeEntryOrRaw: BTNRep> | R
- ): keyNodeEntryOrRaw is BinaryTreeNode | null {
- return keyNodeEntryOrRaw === null || this.isRealNode(keyNodeEntryOrRaw);
+ isRealNodeOrNull(keyNodeOrEntry: BTNRep>): keyNodeOrEntry is BinaryTreeNode | null {
+ return keyNodeOrEntry === null || this.isRealNode(keyNodeOrEntry);
}
/**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
* The function isNIL checks if a given key, node, entry, or raw value is equal to the _NIL value.
- * @param {BTNRep> | R} keyNodeEntryOrRaw - BTNRep> | R
- * @returns The function is checking if the `keyNodeEntryOrRaw` parameter is equal to the `_NIL`
+ * @param {BTNRep>} keyNodeOrEntry - BTNRep>
+ * @returns The function is checking if the `keyNodeOrEntry` parameter is equal to the `_NIL`
* property of the current object and returning a boolean value based on that comparison.
*/
- isNIL(keyNodeEntryOrRaw: BTNRep> | R): boolean {
- return keyNodeEntryOrRaw === this._NIL;
- }
-
- isRange(
- keyNodeEntryRawOrPredicate: BTNRep> | R | NodePredicate> | Range
- ): keyNodeEntryRawOrPredicate is Range {
- return keyNodeEntryRawOrPredicate instanceof Range;
+ isNIL(keyNodeOrEntry: BTNRep>): boolean {
+ return keyNodeOrEntry === this._NIL;
}
/**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
+ * The function `isRange` checks if the input parameter is an instance of the `Range` class.
+ * @param {BTNRep> | NodePredicate> | Range}
+ * keyNodeEntryOrPredicate - The `keyNodeEntryOrPredicate` parameter in the `isRange` function can be
+ * of type `BTNRep>`, `NodePredicate>`, or
+ * `Range`. The function checks if the `keyNodeEntry
+ * @returns The `isRange` function is checking if the `keyNodeEntryOrPredicate` parameter is an
+ * instance of the `Range` class. If it is an instance of `Range`, the function will return `true`,
+ * indicating that the parameter is a `Range`. If it is not an instance of `Range`, the function
+ * will return `false`.
+ */
+ isRange(
+ keyNodeEntryOrPredicate: BTNRep> | NodePredicate> | Range
+ ): keyNodeEntryOrPredicate is Range {
+ return keyNodeEntryOrPredicate instanceof Range;
+ }
+
+ /**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
* The function determines whether a given key, node, entry, or raw data is a leaf node in a binary
* tree.
- * @param {BTNRep> | R} keyNodeEntryOrRaw - The parameter
- * `keyNodeEntryOrRaw` can be of type `BTNRep>` or `R`. It represents a
+ * @param {BTNRep>} keyNodeOrEntry - The parameter
+ * `keyNodeOrEntry` can be of type `BTNRep>` or `R`. It represents a
* key, node, entry, or raw data in a binary tree structure. The function `isLeaf` checks whether the
* provided
* @returns The function `isLeaf` returns a boolean value indicating whether the input
- * `keyNodeEntryOrRaw` is a leaf node in a binary tree.
+ * `keyNodeOrEntry` is a leaf node in a binary tree.
*/
- isLeaf(keyNodeEntryOrRaw: BTNRep> | R): boolean {
- keyNodeEntryOrRaw = this.ensureNode(keyNodeEntryOrRaw);
- if (keyNodeEntryOrRaw === undefined) return false;
- if (keyNodeEntryOrRaw === null) return true;
- return !this.isRealNode(keyNodeEntryOrRaw.left) && !this.isRealNode(keyNodeEntryOrRaw.right);
+ isLeaf(keyNodeOrEntry: BTNRep>): boolean {
+ keyNodeOrEntry = this.ensureNode(keyNodeOrEntry);
+ if (keyNodeOrEntry === undefined) return false;
+ if (keyNodeOrEntry === null) return true;
+ return !this.isRealNode(keyNodeOrEntry.left) && !this.isRealNode(keyNodeOrEntry.right);
}
/**
+ * Time Complexity: O(1)
+ * Space Complexity: O(1)
+ *
* The function `isEntry` checks if the input is a BTNEntry object by verifying if it is an array
* with a length of 2.
- * @param {BTNRep> | R} keyNodeEntryOrRaw - The `keyNodeEntryOrRaw`
+ * @param {BTNRep>} keyNodeOrEntry - The `keyNodeOrEntry`
* parameter in the `isEntry` function can be of type `BTNRep>` or type `R`.
- * The function checks if the provided `keyNodeEntryOrRaw` is of type `BTN
- * @returns The `isEntry` function is checking if the `keyNodeEntryOrRaw` parameter is an array
+ * The function checks if the provided `keyNodeOrEntry` is of type `BTN
+ * @returns The `isEntry` function is checking if the `keyNodeOrEntry` parameter is an array
* with a length of 2. If it is, then it returns `true`, indicating that the parameter is of type
* `BTNEntry