From 1f8fc1487ce5d93dbb428ec3683cf7ec1b793db5 Mon Sep 17 00:00:00 2001 From: Revone Date: Thu, 11 Jan 2024 20:13:02 +0800 Subject: [PATCH] Refactor: Due to critical issues in the previous implementation of the Red-Black Tree, it has been deprecated and replaced with a new implementation of both the Red-Black Tree and TreeMultiMap. --- CHANGELOG.md | 2 +- package.json | 2 +- .../binary-tree/binary-tree.ts | 38 +- src/data-structures/binary-tree/rb-tree.ts | 910 +++++++++--------- .../binary-tree/tree-multi-map.ts | 171 ++-- .../binary-tree/rb-tree.test.ts | 42 +- .../binary-tree/overall.test.ts | 44 +- .../binary-tree/rb-tree.test.ts | 275 ++++-- .../binary-tree/tree-multi-map.test.ts | 505 ++++++---- 9 files changed, 1114 insertions(+), 875 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 428fdb4..ea9ffa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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.50.4](https://github.com/zrwusa/data-structure-typed/compare/v1.35.0...main) (upcoming) +## [v1.50.5](https://github.com/zrwusa/data-structure-typed/compare/v1.35.0...main) (upcoming) ### Changes diff --git a/package.json b/package.json index dcbcca0..d305342 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "data-structure-typed", - "version": "1.50.4", + "version": "1.50.5", "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", diff --git a/src/data-structures/binary-tree/binary-tree.ts b/src/data-structures/binary-tree/binary-tree.ts index ac5e7aa..54441ef 100644 --- a/src/data-structures/binary-tree/binary-tree.ts +++ b/src/data-structures/binary-tree/binary-tree.ts @@ -934,7 +934,7 @@ export class BinaryTree< if (iterationType === IterationType.RECURSIVE) { const dfs = (cur: NODE | null | undefined, min: number, max: number): boolean => { - if (!cur) return true; + if (!this.isRealNode(cur)) return true; const numKey = this.extractor(cur.key); if (numKey <= min || numKey >= max) return false; return dfs(cur.left, min, numKey) && dfs(cur.right, numKey, max); @@ -949,14 +949,14 @@ export class BinaryTree< let prev = checkMax ? Number.MAX_SAFE_INTEGER : Number.MIN_SAFE_INTEGER; // @ts-ignore let curr: NODE | null | undefined = beginRoot; - while (curr || stack.length > 0) { - while (curr) { + while (this.isRealNode(curr) || stack.length > 0) { + while (this.isRealNode(curr)) { stack.push(curr); curr = curr.left; } curr = stack.pop()!; const numKey = this.extractor(curr.key); - if (!curr || (!checkMax && prev >= numKey) || (checkMax && prev <= numKey)) return false; + if (!this.isRealNode(curr) || (!checkMax && prev >= numKey) || (checkMax && prev <= numKey)) return false; prev = numKey; curr = curr.right; } @@ -1025,7 +1025,7 @@ export class BinaryTree< if (iterationType === IterationType.RECURSIVE) { const _getMaxHeight = (cur: NODE | null | undefined): number => { - if (!cur) return -1; + if (!this.isRealNode(cur)) return -1; const leftHeight = _getMaxHeight(cur.left); const rightHeight = _getMaxHeight(cur.right); return Math.max(leftHeight, rightHeight) + 1; @@ -1039,8 +1039,8 @@ export class BinaryTree< while (stack.length > 0) { const { node, depth } = stack.pop()!; - if (node.left) stack.push({ node: node.left, depth: depth + 1 }); - if (node.right) stack.push({ node: node.right, depth: depth + 1 }); + if (this.isRealNode(node.left)) stack.push({ node: node.left, depth: depth + 1 }); + if (this.isRealNode(node.right)) stack.push({ node: node.right, depth: depth + 1 }); maxHeight = Math.max(maxHeight, depth); } @@ -1354,34 +1354,34 @@ export class BinaryTree< switch (pattern) { case 'in': if (includeNull) { - if (node && this.isNodeOrNull(node.left)) _traverse(node.left); + if (this.isRealNode(node) && this.isNodeOrNull(node.left)) _traverse(node.left); this.isNodeOrNull(node) && ans.push(callback(node)); - if (node && this.isNodeOrNull(node.right)) _traverse(node.right); + if (this.isRealNode(node) && this.isNodeOrNull(node.right)) _traverse(node.right); } else { - if (node && node.left) _traverse(node.left); + if (this.isRealNode(node) && this.isRealNode(node.left)) _traverse(node.left); this.isRealNode(node) && ans.push(callback(node)); - if (node && node.right) _traverse(node.right); + if (this.isRealNode(node) && this.isRealNode(node.right)) _traverse(node.right); } break; case 'pre': if (includeNull) { this.isNodeOrNull(node) && ans.push(callback(node)); - if (node && this.isNodeOrNull(node.left)) _traverse(node.left); - if (node && this.isNodeOrNull(node.right)) _traverse(node.right); + if (this.isRealNode(node) && this.isNodeOrNull(node.left)) _traverse(node.left); + if (this.isRealNode(node) && this.isNodeOrNull(node.right)) _traverse(node.right); } else { this.isRealNode(node) && ans.push(callback(node)); - if (node && node.left) _traverse(node.left); - if (node && node.right) _traverse(node.right); + if (this.isRealNode(node) && this.isRealNode(node.left)) _traverse(node.left); + if (this.isRealNode(node) && this.isRealNode(node.right)) _traverse(node.right); } break; case 'post': if (includeNull) { - if (node && this.isNodeOrNull(node.left)) _traverse(node.left); - if (node && this.isNodeOrNull(node.right)) _traverse(node.right); + if (this.isRealNode(node) && this.isNodeOrNull(node.left)) _traverse(node.left); + if (this.isRealNode(node) && this.isNodeOrNull(node.right)) _traverse(node.right); this.isNodeOrNull(node) && ans.push(callback(node)); } else { - if (node && node.left) _traverse(node.left); - if (node && node.right) _traverse(node.right); + if (this.isRealNode(node) && this.isRealNode(node.left)) _traverse(node.left); + if (this.isRealNode(node) && this.isRealNode(node.right)) _traverse(node.right); this.isRealNode(node) && ans.push(callback(node)); } diff --git a/src/data-structures/binary-tree/rb-tree.ts b/src/data-structures/binary-tree/rb-tree.ts index 1330d83..8f1dcbe 100644 --- a/src/data-structures/binary-tree/rb-tree.ts +++ b/src/data-structures/binary-tree/rb-tree.ts @@ -1,21 +1,13 @@ -/** - * data-structure-typed - * - * @author Tyler Zeng - * @copyright Copyright (c) 2022 Tyler Zeng - * @license MIT License - */ - -import { +import type { BinaryTreeDeleteResult, BSTNKeyOrNode, BTNCallback, KeyOrNodeOrEntry, - RBTNColor, RBTreeOptions, RedBlackTreeNested, RedBlackTreeNodeNested } from '../../types'; +import { RBTNColor } from '../../types'; import { BST, BSTNode } from './bst'; import { IBinaryTree } from '../../interfaces'; @@ -44,7 +36,7 @@ export class RedBlackTreeNode< /** * The function returns the color value of a variable. - * @returns The color value stored in the protected variable `_color`. + * @returns The color value stored in the private variable `_color`. */ get color(): RBTNColor { return this._color; @@ -59,13 +51,6 @@ export class RedBlackTreeNode< } } -/** - * 1. Each node is either red or black. - * 2. The root node is always black. - * 3. Leaf nodes are typically Sentinel nodes and are considered black. - * 4. Red nodes must have black children. - * 5. Black balance: Every path from any node to each of its leaf nodes contains the same number of black nodes. - */ export class RedBlackTree< K = any, V = any, @@ -75,40 +60,42 @@ export class RedBlackTree< extends BST implements IBinaryTree { /** - * This is the constructor function for a Red-Black Tree data structure in TypeScript, which - * initializes the tree with optional nodes and options. - * @param [keysOrNodesOrEntries] - The `keysOrNodesOrEntries` parameter is an optional iterable of `KeyOrNodeOrEntry` - * objects. It represents the initial nodes that will be added to the RBTree during its - * construction. If this parameter is provided, the `addMany` method is called to add all the - * nodes to the - * @param [options] - The `options` parameter is an optional object that allows you to customize the - * behavior of the RBTree. It is of type `Partial`, which means that you can provide - * only a subset of the properties defined in the `RBTreeOptions` interface. + * This is the constructor function for a Red-Black Tree data structure in TypeScript. + * @param keysOrNodesOrEntries - The `keysOrNodesOrEntries` parameter is an iterable object that can + * contain keys, nodes, or entries. It is used to initialize the RBTree with the provided keys, + * nodes, or entries. + * @param [options] - The `options` parameter is an optional object that can be passed to the + * constructor. It allows you to customize the behavior of the RBTree. It can include properties such + * as `compareKeys`, `compareValues`, `allowDuplicates`, etc. These properties define how the RBTree + * should compare keys and */ constructor(keysOrNodesOrEntries: Iterable> = [], options?: RBTreeOptions) { super([], options); - this._root = this._Sentinel; - if (keysOrNodesOrEntries) super.addMany(keysOrNodesOrEntries); + this._root = this.SENTINEL; + + if (keysOrNodesOrEntries) { + this.addMany(keysOrNodesOrEntries); + } } - protected _Sentinel: NODE = new RedBlackTreeNode(NaN as K) as unknown as NODE; + protected _SENTINEL: NODE = new RedBlackTreeNode(NaN as K) as unknown as NODE; /** - * The function returns the value of the `_Sentinel` property. - * @returns The method is returning the value of the `_Sentinel` property. + * The function returns the value of the _SENTINEL property. + * @returns The method is returning the value of the `_SENTINEL` property. */ - get Sentinel(): NODE { - return this._Sentinel; + get SENTINEL(): NODE { + return this._SENTINEL; } - protected _root: NODE; + protected _root: NODE | undefined; /** - * The function returns the root node. - * @returns The root node of the data structure. + * 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. */ - get root(): NODE { + get root(): NODE | undefined { return this._root; } @@ -124,13 +111,13 @@ export class RedBlackTree< /** * The function creates a new Red-Black Tree node with the specified key, value, and color. - * @param {K} key - The key parameter is the key value associated with the node. It is used to - * identify and compare nodes in the Red-Black Tree. + * @param {K} key - The key parameter represents the key of the node being created. It is of type K, + * which is a generic type representing the key's data type. * @param {V} [value] - The `value` parameter is an optional parameter that represents the value - * associated with the node. It is of type `V`, which is a generic type that can be replaced with any - * specific type when using the `createNode` method. + * associated with the key in the node. It is not required and can be omitted if not needed. * @param {RBTNColor} color - The "color" parameter is used to specify the color of the node in a - * Red-Black Tree. It can be either "RED" or "BLACK". By default, the color is set to "BLACK". + * Red-Black Tree. It is an optional parameter with a default value of "RBTNColor.BLACK". The color + * can be either "RBTNColor.RED" or "RBTNColor.BLACK". * @returns The method is returning a new instance of a RedBlackTreeNode with the specified key, * value, and color. */ @@ -139,10 +126,10 @@ export class RedBlackTree< } /** - * The function creates a Red-Black Tree with the specified options and returns it. - * @param {RBTreeOptions} [options] - The `options` parameter is an optional object that can be - * passed to the `createTree` function. It is used to customize the behavior of the `RedBlackTree` - * class. + * The function creates a Red-Black Tree with the given options and returns it. + * @param [options] - The `options` parameter is an optional object that contains configuration + * options for creating the Red-Black Tree. It is of type `RBTreeOptions`, where `K` represents + * the type of keys in the tree. * @returns a new instance of a RedBlackTree object. */ override createTree(options?: RBTreeOptions): TREE { @@ -153,12 +140,19 @@ export class RedBlackTree< } /** - * The function `keyValueOrEntryToNode` takes an keyOrNodeOrEntry and converts it into a node object if possible. - * @param keyOrNodeOrEntry - The `keyOrNodeOrEntry` parameter is of type `KeyOrNodeOrEntry`, where: - * @param {V} [value] - The `value` parameter is an optional value that can be passed to the - * `keyValueOrEntryToNode` function. It represents the value associated with the keyOrNodeOrEntry node. If a value - * is provided, it will be used when creating the new node. If no value is provided, the new node - * @returns a node of type NODE or undefined. + * Time Complexity: O(1) + * Space Complexity: O(1) + */ + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function `keyValueOrEntryToNode` takes a key, value, or entry and returns a node if it is + * valid, otherwise it returns undefined. + * @param {KeyOrNodeOrEntry} keyOrNodeOrEntry - The key, value, or entry to convert. + * @param {V} [value] - The value associated with the key (if `keyOrNodeOrEntry` is a key). + * @returns {NODE | undefined} - The corresponding Red-Black Tree node, or `undefined` if conversion fails. */ override keyValueOrEntryToNode(keyOrNodeOrEntry: KeyOrNodeOrEntry, value?: V): NODE | undefined { let node: NODE | undefined; @@ -183,203 +177,68 @@ export class RedBlackTree< } /** - * The function checks if an keyOrNodeOrEntry is an instance of the RedBlackTreeNode class. - * @param keyOrNodeOrEntry - The `keyOrNodeOrEntry` parameter is of type `KeyOrNodeOrEntry`. - * @returns a boolean value indicating whether the keyOrNodeOrEntry is an instance of the RedBlackTreeNode - * class. + * Time Complexity: O(1) + * Space Complexity: O(1) + * / + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * + * The function checks if the input is an instance of the RedBlackTreeNode class. + * @param {KeyOrNodeOrEntry} keyOrNodeOrEntry - The object to check. + * @returns {boolean} - `true` if the object is a Red-Black Tree node, `false` otherwise. */ override isNode(keyOrNodeOrEntry: KeyOrNodeOrEntry): keyOrNodeOrEntry is NODE { return keyOrNodeOrEntry instanceof RedBlackTreeNode; } /** + * Time Complexity: O(1) + * Space Complexity: O(1) + */ + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + * * The function checks if a given node is a real node in a Red-Black Tree. * @param {NODE | undefined} node - The `node` parameter is of type `NODE | undefined`, which means * it can either be of type `NODE` or `undefined`. * @returns a boolean value. */ override isRealNode(node: NODE | undefined): node is NODE { - if (node === this._Sentinel || node === undefined) return false; + if (node === this._SENTINEL || node === undefined) return false; return node instanceof RedBlackTreeNode; } /** * Time Complexity: O(log n) * Space Complexity: O(1) - * On average (where n is the number of nodes in the tree) */ /** * Time Complexity: O(log n) * Space Complexity: O(1) * - * The `add` function adds a new node to a binary search tree and performs necessary rotations and - * color changes to maintain the red-black tree properties. - * @param keyOrNodeOrEntry - The `keyOrNodeOrEntry` parameter can be either a key, a node, or an - * entry. - * @param {V} [value] - The `value` parameter represents the value associated with the key that is - * being added to the binary search tree. - * @returns The method `add` returns either the newly added node (`NODE`) or `undefined`. - */ - override add(keyOrNodeOrEntry: KeyOrNodeOrEntry, value?: V): boolean { - const newNode = this.keyValueOrEntryToNode(keyOrNodeOrEntry, value); - if (newNode === undefined) return false; - - newNode.left = this._Sentinel; - newNode.right = this._Sentinel; - - let y: NODE | undefined = undefined; - let x: NODE | undefined = this.root; - - while (x !== this._Sentinel) { - y = x; - if (x) { - if (newNode.key < x.key) { - x = x.left; - } else if (newNode.key > x.key) { - x = x?.right; - } else { - if (newNode !== x) { - this._replaceNode(x, newNode); - } - return false; - } - } - } - - newNode.parent = y; - if (y === undefined) { - this._setRoot(newNode); - } else if (newNode.key < y.key) { - y.left = newNode; - } else { - y.right = newNode; - } - - if (newNode.parent === undefined) { - newNode.color = RBTNColor.BLACK; - this._size++; - return false; - } - - if (newNode.parent.parent === undefined) { - this._size++; - return false; - } - - this._fixInsert(newNode); - this._size++; - return true; - } - - /** - * Time Complexity: O(log n) - * Space Complexity: O(1) - */ - - /** - * Time Complexity: O(log n) - * Space Complexity: O(1) - * - * The `delete` function removes a node from a binary tree based on a given identifier and updates - * the tree accordingly. - * @param {ReturnType | null | undefined} identifier - The `identifier` parameter is the value - * that you want to use to identify the node that you want to delete from the binary tree. It can be - * of any type that is returned by the callback function `C`. It can also be `null` or `undefined` if - * you don't want to - * @param {C} callback - The `callback` parameter is a function that takes a node of type `NODE` and - * returns a value of type `ReturnType`. It is used to determine if a node should be deleted based - * on its identifier. The `callback` function is optional and defaults to `this._defaultOneParam - * @returns an array of `BinaryTreeDeleteResult`. - */ - delete>( - identifier: ReturnType | null | undefined, - callback: C = this._defaultOneParamCallback as C - ): BinaryTreeDeleteResult[] { - const ans: BinaryTreeDeleteResult[] = []; - if (identifier === null) return ans; - const helper = (node: NODE | undefined): void => { - let z: NODE = this._Sentinel; - let x: NODE | undefined, y: NODE; - while (node !== this._Sentinel) { - if (node && callback(node) === identifier) { - z = node; - } - - if (node && identifier && callback(node) <= identifier) { - node = node.right; - } else { - node = node?.left; - } - } - - if (z === this._Sentinel) { - this._size--; - return; - } - - y = z; - let yOriginalColor: number = y.color; - if (z.left === this._Sentinel) { - x = z.right; - this._rbTransplant(z, z.right!); - } else if (z.right === this._Sentinel) { - x = z.left; - this._rbTransplant(z, z.left!); - } else { - y = this.getLeftMost(z.right)!; - yOriginalColor = y.color; - x = y.right; - if (y.parent === z) { - x!.parent = y; - } else { - this._rbTransplant(y, y.right!); - y.right = z.right; - y.right!.parent = y; - } - - this._rbTransplant(z, y); - y.left = z.left; - y.left!.parent = y; - y.color = z.color; - } - if (yOriginalColor === RBTNColor.BLACK) { - this._fixDelete(x!); - } - this._size--; - ans.push({ deleted: z, needBalanced: undefined }); - }; - helper(this.root); - return ans; - } - - /** - * Time Complexity: O(log n) - * Space Complexity: O(1) - */ - - /** - * Time Complexity: O(log n) - * Space Complexity: O(1) - * - * The function `getNode` retrieves a single node from a binary tree based on a given identifier and + * The `getNode` function retrieves a node from a Red-Black Tree based on the provided identifier and * callback function. - * @param {ReturnType | undefined} identifier - The `identifier` parameter is the value used to - * identify the node you want to retrieve. It can be of any type that is the return type of the `C` - * callback function. If the `identifier` is `undefined`, it means you want to retrieve the first - * node that matches the other criteria + * @param {ReturnType | undefined} identifier - The `identifier` parameter is the value or key + * that you want to search for in the binary search tree. It can be of any type that is compatible + * with the type of nodes in the tree. * @param {C} callback - The `callback` parameter is a function that will be called for each node in - * the binary tree. It is used to determine if a node matches the given identifier. The `callback` - * function should take a single parameter of type `NODE` (the type of the nodes in the binary tree) and - * @param {K | NODE | undefined} beginRoot - The `beginRoot` parameter is the starting point for - * searching for a node in a binary tree. It can be either a key value or a node object. If it is not - * provided, the search will start from the root of the binary tree. - * @param iterationType - The `iterationType` parameter is a variable that determines the type of - * iteration to be performed when searching for nodes in the binary tree. It is used in the - * `getNodes` method, which is called within the `getNode` method. - * @returns a value of type `NODE`, `null`, or `undefined`. + * the tree. It is used to determine whether a node matches the given identifier. The `callback` + * function should take a node as its parameter and return a value that can be compared to the + * `identifier` parameter. + * @param beginRoot - The `beginRoot` parameter is the starting point for the search in the binary + * search tree. It can be either a key or a node. If it is a key, it will be converted to a node + * using the `ensureNode` method. If it is not provided, the `root` + * @param iterationType - The `iterationType` parameter is used to specify the type of iteration to + * be performed when searching for nodes in the binary search tree. It is an optional parameter and + * its default value is taken from the `iterationType` property of the class. + * @returns The method is returning a value of type `NODE | null | undefined`. */ - getNode>( + override getNode>( identifier: ReturnType | undefined, callback: C = this._defaultOneParamCallback as C, beginRoot: BSTNKeyOrNode = this.root, @@ -399,10 +258,11 @@ export class RedBlackTree< * Time Complexity: O(1) * Space Complexity: O(1) * - * The "clear" function sets the root node to the sentinel node and resets the size to 0. + * The "clear" function sets the root node of a data structure to a sentinel value and resets the + * size counter to zero. */ override clear() { - this._root = this._Sentinel; + this._root = this.SENTINEL; this._size = 0; } @@ -415,32 +275,120 @@ export class RedBlackTree< * Time Complexity: O(log n) * Space Complexity: O(1) * - * The function returns the predecessor of a given node in a red-black tree. - * @param {RedBlackTreeNode} x - The parameter `x` is of type `RedBlackTreeNode`, which represents a node in a - * Red-Black Tree. - * @returns the predecessor of the given RedBlackTreeNode 'x'. + * The function adds a new node to a Red-Black Tree data structure and returns a boolean indicating + * whether the operation was successful. + * @param keyOrNodeOrEntry - The `keyOrNodeOrEntry` parameter can be either a key, a node, or an + * entry. + * @param {V} [value] - The `value` parameter is the value associated with the key that is being + * added to the tree. + * @returns The method is returning a boolean value. It returns true if the node was successfully + * added or updated, and false otherwise. */ - override getPredecessor(x: NODE): NODE { - if (this.isRealNode(x.left)) { - return this.getRightMost(x.left)!; - } + override add(keyOrNodeOrEntry: KeyOrNodeOrEntry, value?: V): boolean { + const newNode = this.keyValueOrEntryToNode(keyOrNodeOrEntry, value); + if (!this.isRealNode(newNode)) return false; - let y: NODE | undefined = x.parent; - while (this.isRealNode(y) && x === y.left) { - x = y!; - y = y!.parent; - } + const insertStatus = this._insert(newNode); - return y!; + if (insertStatus === 'inserted') { + // Ensure the root is black + if (this.isRealNode(this._root)) { + this._root.color = RBTNColor.BLACK; + } else { + return false; + } + this._size++; + return true; + } else return insertStatus === 'updated'; } /** - * The function sets the root node of a tree structure and updates the parent property of the new - * root node. - * @param {NODE} v - The parameter "v" is of type "NODE", which represents a node in a data - * structure. + * Time Complexity: O(log n) + * Space Complexity: O(1) */ - protected override _setRoot(v: NODE) { + + /** + * Time Complexity: O(log n) + * Space Complexity: O(1) + * + * The function `delete` in a binary tree class deletes a node from the tree and fixes the tree if + * necessary. + * @param {ReturnType | null | undefined} identifier - The `identifier` parameter is the + * identifier of the node that needs to be deleted from the binary tree. It can be of any type that + * is returned by the callback function `C`. It can also be `null` or `undefined` if the node to be + * deleted is not found. + * @param {C} callback - The `callback` parameter is a function that is used to retrieve a node from + * the binary tree based on its identifier. It is an optional parameter and if not provided, the + * `_defaultOneParamCallback` function is used as the default callback. The callback function should + * return the identifier of the node to + * @returns an array of BinaryTreeDeleteResult objects. + */ + override delete>( + identifier: ReturnType | null | undefined, + callback: C = this._defaultOneParamCallback as C + ): BinaryTreeDeleteResult[] { + if (identifier === null) return []; + const results: BinaryTreeDeleteResult[] = []; + + const nodeToDelete = this.isRealNode(identifier) ? identifier : this.getNode(identifier, callback); + + if (!nodeToDelete) { + return results; + } + + let originalColor = nodeToDelete.color; + let replacementNode: NODE | undefined; + + if (!this.isRealNode(nodeToDelete.left)) { + replacementNode = nodeToDelete.right; + this._transplant(nodeToDelete, nodeToDelete.right); + } else if (!this.isRealNode(nodeToDelete.right)) { + replacementNode = nodeToDelete.left; + this._transplant(nodeToDelete, nodeToDelete.left); + } else { + const successor = this.getLeftMost(nodeToDelete.right); + if (successor) { + originalColor = successor.color; + replacementNode = successor.right; + + if (successor.parent === nodeToDelete) { + if (this.isRealNode(replacementNode)) { + replacementNode.parent = successor; + } + } else { + this._transplant(successor, successor.right); + successor.right = nodeToDelete.right; + if (this.isRealNode(successor.right)) { + successor.right.parent = successor; + } + } + + this._transplant(nodeToDelete, successor); + successor.left = nodeToDelete.left; + if (this.isRealNode(successor.left)) { + successor.left.parent = successor; + } + successor.color = nodeToDelete.color; + } + } + this._size--; + + // If the original color was black, fix the tree + if (originalColor === RBTNColor.BLACK) { + this._deleteFixup(replacementNode); + } + + results.push({ deleted: nodeToDelete, needBalanced: undefined }); + + return results; + } + + /** + * 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. + */ + protected override _setRoot(v: NODE | undefined) { if (v) { v.parent = undefined; } @@ -456,60 +404,18 @@ export class RedBlackTree< * Time Complexity: O(1) * Space Complexity: O(1) * - * The function performs a left rotation on a binary tree node. - * @param {RedBlackTreeNode} x - The parameter `x` is of type `NODE`, which likely represents a node in a binary tree. + * 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 + * the data structure. + * @param {NODE} newNode - The `newNode` parameter is the new node that will replace the old node in + * the data structure. + * @returns The method is returning the result of calling the `_replaceNode` method from the + * superclass, with the `oldNode` and `newNode` parameters. */ - protected _leftRotate(x: NODE): void { - if (x.right) { - const y: NODE = x.right; - x.right = y.left; - if (y.left !== this._Sentinel) { - if (y.left) y.left.parent = x; - } - y.parent = x.parent; - if (x.parent === undefined) { - this._setRoot(y); - } else if (x === x.parent.left) { - x.parent.left = y; - } else { - x.parent.right = y; - } - y.left = x; - x.parent = y; - } - } + protected override _replaceNode(oldNode: NODE, newNode: NODE): NODE { + newNode.color = oldNode.color; - /** - * Time Complexity: O(1) - * Space Complexity: O(1) - */ - - /** - * Time Complexity: O(1) - * Space Complexity: O(1) - * - * The function performs a right rotation on a red-black tree node. - * @param {RedBlackTreeNode} x - x is a RedBlackTreeNode, which represents the node that needs to be right - * rotated. - */ - protected _rightRotate(x: NODE): void { - if (x.left) { - const y: NODE = x.left; - x.left = y.right; - if (y.right !== this._Sentinel) { - if (y.right) y.right.parent = x; - } - y.parent = x.parent; - if (x.parent === undefined) { - this._setRoot(y); - } else if (x === x.parent.right) { - x.parent.right = y; - } else { - x.parent.left = y; - } - y.right = x; - x.parent = y; - } + return super._replaceNode(oldNode, newNode); } /** @@ -521,136 +427,45 @@ export class RedBlackTree< * Time Complexity: O(log n) * Space Complexity: O(1) * - * The `_fixInsert` function is used to fix the red-black tree after an insertion operation. - * @param {RedBlackTreeNode} k - The parameter `k` is a RedBlackTreeNode object, which represents a node in a - * red-black tree. + * The `_insert` function inserts or updates a node in 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 a + * binary search tree. It contains a `key` property that is used to determine the position of the + * node in the tree. + * @returns {'inserted' | 'updated'} - The result of the insertion. */ - protected _fixInsert(k: NODE): void { - let u: NODE | undefined; - while (k.parent && k.parent.color === RBTNColor.RED) { - if (k.parent.parent && k.parent === k.parent.parent.right) { - u = k.parent.parent.left; + protected _insert(node: NODE): 'inserted' | 'updated' { + let current = this.root; + let parent: NODE | undefined = undefined; - if (u && u.color === RBTNColor.RED) { - // Delay color flip - k.parent.color = RBTNColor.BLACK; - u.color = RBTNColor.BLACK; - k.parent.parent.color = RBTNColor.RED; - k = k.parent.parent; - } else { - if (k === k.parent.left) { - k = k.parent; - this._rightRotate(k); - } - - // Check color before rotation - if (k.parent!.color === RBTNColor.RED) { - k.parent!.color = RBTNColor.BLACK; - k.parent!.parent!.color = RBTNColor.RED; - } - this._leftRotate(k.parent!.parent!); - } + while (this.isRealNode(current)) { + parent = current; + if (node.key < current.key) { + current = current.left ?? this.SENTINEL; + } else if (node.key > current.key) { + current = current.right ?? this.SENTINEL; } else { - u = k.parent!.parent!.right; - - if (u && u.color === RBTNColor.RED) { - // Delay color flip - k.parent.color = RBTNColor.BLACK; - u.color = RBTNColor.BLACK; - k.parent.parent!.color = RBTNColor.RED; - k = k.parent.parent!; - } else { - if (k === k.parent.right) { - k = k.parent; - this._leftRotate(k); - } - - // Check color before rotation - if (k.parent!.color === RBTNColor.RED) { - k.parent!.color = RBTNColor.BLACK; - k.parent!.parent!.color = RBTNColor.RED; - } - this._rightRotate(k.parent!.parent!); - } - } - - if (k === this.root) { - break; + this._replaceNode(current, node); + return 'updated'; } } - this.root.color = RBTNColor.BLACK; - } - /** - * Time Complexity: O(log n) - * Space Complexity: O(1) - */ + node.parent = parent; - /** - * Time Complexity: O(log n) - * Space Complexity: O(1) - * - * The function `_fixDelete` is used to fix the red-black tree after a node deletion. - * @param {RedBlackTreeNode} x - The parameter `x` represents a node in a Red-Black Tree (RBT). - */ - protected _fixDelete(x: NODE): void { - let s: NODE | undefined; - while (x !== this.root && x.color === RBTNColor.BLACK) { - if (x.parent && x === x.parent.left) { - s = x.parent.right!; - if (s.color === 1) { - s.color = RBTNColor.BLACK; - x.parent.color = RBTNColor.RED; - this._leftRotate(x.parent); - s = x.parent.right!; - } - - if (s.left !== undefined && s.left.color === RBTNColor.BLACK && s.right && s.right.color === RBTNColor.BLACK) { - s.color = RBTNColor.RED; - x = x.parent; - } else { - if (s.right && s.right.color === RBTNColor.BLACK) { - if (s.left) s.left.color = RBTNColor.BLACK; - s.color = RBTNColor.RED; - this._rightRotate(s); - s = x.parent.right; - } - - if (s) s.color = x.parent.color; - x.parent.color = RBTNColor.BLACK; - if (s && s.right) s.right.color = RBTNColor.BLACK; - this._leftRotate(x.parent); - x = this.root; - } - } else { - s = x.parent!.left!; - if (s.color === 1) { - s.color = RBTNColor.BLACK; - x.parent!.color = RBTNColor.RED; - this._rightRotate(x.parent!); - s = x.parent!.left; - } - - if (s && s.right && s.right.color === RBTNColor.BLACK && s.right.color === RBTNColor.BLACK) { - s.color = RBTNColor.RED; - x = x.parent!; - } else { - if (s && s.left && s.left.color === RBTNColor.BLACK) { - if (s.right) s.right.color = RBTNColor.BLACK; - s.color = RBTNColor.RED; - this._leftRotate(s); - s = x.parent!.left; - } - - if (s) s.color = x.parent!.color; - x.parent!.color = RBTNColor.BLACK; - if (s && s.left) s.left.color = RBTNColor.BLACK; - this._rightRotate(x.parent!); - x = this.root; - } - } + if (!parent) { + this._setRoot(node); + } else if (node.key < parent.key) { + parent.left = node; + } else { + parent.right = node; } - x.color = RBTNColor.BLACK; + + node.left = this.SENTINEL; + node.right = this.SENTINEL; + node.color = RBTNColor.RED; + + this._insertFixup(node); + return 'inserted'; } /** @@ -662,33 +477,260 @@ export class RedBlackTree< * Time Complexity: O(1) * Space Complexity: O(1) * - * The function `_rbTransplant` replaces one node in a red-black tree with another node. - * @param {RedBlackTreeNode} u - The parameter "u" represents a RedBlackTreeNode object. - * @param {RedBlackTreeNode} v - The parameter "v" is a RedBlackTreeNode object. + * 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`. */ - protected _rbTransplant(u: NODE, v: NODE): void { - if (u.parent === undefined) { + protected _transplant(u: NODE, v: NODE | undefined): void { + if (!u.parent) { this._setRoot(v); } else if (u === u.parent.left) { u.parent.left = v; } else { u.parent.right = v; } - v.parent = u.parent; + + if (v) { + v.parent = u.parent; + } } /** - * 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 a - * data structure. It is of type `NODE`, which is the type of the nodes in the data structure. - * @param {NODE} newNode - The `newNode` parameter is the 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, passing in the `oldNode` and `newNode` as arguments. + * Time Complexity: O(log n) + * Space Complexity: O(1) */ - protected _replaceNode(oldNode: NODE, newNode: NODE): NODE { - newNode.color = oldNode.color; - return super._replaceNode(oldNode, newNode); + /** + * Time Complexity: O(log n) + * 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. It can + * either be a valid node object or `undefined`. + */ + protected _insertFixup(z: NODE | undefined): void { + // Continue fixing the tree as long as the parent of z is red + while (z?.parent?.color === RBTNColor.RED) { + // Check if the parent of z is the left child of its parent + if (z.parent === z.parent.parent?.left) { + // Case 1: The uncle (y) of z is red + const y = z.parent.parent.right; + if (y?.color === RBTNColor.RED) { + // Set colors to restore properties of Red-Black Tree + z.parent.color = RBTNColor.BLACK; + y.color = RBTNColor.BLACK; + z.parent.parent.color = RBTNColor.RED; + // Move up the tree to continue fixing + z = z.parent.parent; + } else { + // Case 2: The uncle (y) of z is black, and z is a right child + if (z === z.parent.right) { + // Perform a left rotation to transform the case into Case 3 + z = z.parent; + this._leftRotate(z); + } + + // Case 3: The uncle (y) of z is black, and z is a left child + // Adjust colors and perform a right rotation + if (z && this.isRealNode(z.parent) && this.isRealNode(z.parent.parent)) { + z.parent.color = RBTNColor.BLACK; + z.parent.parent.color = RBTNColor.RED; + this._rightRotate(z.parent.parent); + } + } + } 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; + if (y?.color === RBTNColor.RED) { + z.parent.color = RBTNColor.BLACK; + y.color = RBTNColor.BLACK; + z.parent.parent!.color = RBTNColor.RED; + z = z.parent.parent; + } else { + if (z === z.parent.left) { + z = z.parent; + this._rightRotate(z); + } + + if (z && this.isRealNode(z.parent) && this.isRealNode(z.parent.parent)) { + z.parent.color = RBTNColor.BLACK; + z.parent.parent.color = RBTNColor.RED; + this._leftRotate(z.parent.parent); + } + } + } + } + + // Ensure that the root is black after fixing + if (this.isRealNode(this._root)) this._root.color = RBTNColor.BLACK; + } + + /** + * Time Complexity: O(log n) + * Space Complexity: O(1) + */ + + /** + * Time Complexity: O(log n) + * Space Complexity: O(1) + * + * 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 Red-Black Tree data + * structure. 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`. + */ + protected _deleteFixup(node: NODE | undefined): void { + // Early exit condition + if (!node || node === this.root || node.color === RBTNColor.BLACK) { + if (node) { + node.color = RBTNColor.BLACK; // Ensure the final node is black + } + return; + } + + while (node && node !== this.root && node.color === RBTNColor.BLACK) { + const parent: NODE | undefined = node.parent; + + if (!parent) { + break; // Ensure the loop terminates if there's an issue with the tree structure + } + + if (node === parent.left) { + let sibling = parent.right; + + // Cases 1 and 2: Sibling is red or both children of sibling are black + if (sibling?.color === RBTNColor.RED) { + sibling.color = RBTNColor.BLACK; + parent.color = RBTNColor.RED; + this._leftRotate(parent); + sibling = parent.right; + } + + // Case 3: Sibling's left child is black + if ((sibling?.left?.color ?? RBTNColor.BLACK) === RBTNColor.BLACK) { + if (sibling) sibling.color = RBTNColor.RED; + node = parent; + } else { + // Case 4: Adjust colors and perform a right rotation + if (sibling?.left) sibling.left.color = RBTNColor.BLACK; + if (sibling) sibling.color = parent.color; + parent.color = RBTNColor.BLACK; + this._rightRotate(parent); + node = this.root; + } + } else { + // Symmetric case for the right child (left and right exchanged) + let sibling = parent.left; + + // Cases 1 and 2: Sibling is red or both children of sibling are black + if (sibling?.color === RBTNColor.RED) { + sibling.color = RBTNColor.BLACK; + if (parent) parent.color = RBTNColor.RED; + this._rightRotate(parent); + if (parent) sibling = parent.left; + } + + // Case 3: Sibling's left child is black + if ((sibling?.right?.color ?? RBTNColor.BLACK) === RBTNColor.BLACK) { + if (sibling) sibling.color = RBTNColor.RED; + node = parent; + } else { + // Case 4: Adjust colors and perform a left rotation + if (sibling?.right) sibling.right.color = RBTNColor.BLACK; + if (sibling) sibling.color = parent.color; + if (parent) parent.color = RBTNColor.BLACK; + this._leftRotate(parent); + node = this.root; + } + } + } + + // Ensure that the final node (possibly the root) is black + if (node) { + node.color = RBTNColor.BLACK; + } + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + */ + + /** + * Time Complexity: O(1) + * 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 + * 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 { + if (!x || !x.right) { + return; + } + + const y = x.right; + x.right = y.left; + + if (this.isRealNode(y.left)) { + y.left.parent = x; + } + + y.parent = x.parent; + + if (!x.parent) { + this._setRoot(y); + } else if (x === x.parent.left) { + x.parent.left = y; + } else { + x.parent.right = y; + } + + y.left = x; + x.parent = y; + } + + /** + * Time Complexity: O(1) + * Space Complexity: O(1) + */ + + /** + * Time Complexity: O(1) + * 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 + * 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 { + if (!y || !y.left) { + return; + } + + const x = y.left; + y.left = x.right; + + if (this.isRealNode(x.right)) { + x.right.parent = y; + } + + x.parent = y.parent; + + if (!y.parent) { + this._setRoot(x); + } else if (y === y.parent.left) { + y.parent.left = x; + } else { + y.parent.right = x; + } + + x.right = y; + y.parent = x; } } diff --git a/src/data-structures/binary-tree/tree-multi-map.ts b/src/data-structures/binary-tree/tree-multi-map.ts index ec32c77..2ac2aba 100644 --- a/src/data-structures/binary-tree/tree-multi-map.ts +++ b/src/data-structures/binary-tree/tree-multi-map.ts @@ -88,10 +88,13 @@ export class TreeMultiMap< * @returns the sum of the count property of all nodes in the tree. */ get count(): number { + return this._count; + } + + getMutableCount(): number { let sum = 0; this.dfs(node => (sum += node.count)); return sum; - // return this._count; } /** @@ -192,14 +195,15 @@ export class TreeMultiMap< */ override add(keyOrNodeOrEntry: KeyOrNodeOrEntry, value?: V, count = 1): boolean { const newNode = this.keyValueOrEntryToNode(keyOrNodeOrEntry, value, count); - if (newNode === undefined) return false; + const orgCount = newNode?.count || 0; + const isSuccessAdded = super.add(newNode); - const orgNodeCount = newNode?.count || 0; - const inserted = super.add(newNode); - if (inserted) { - this._count += orgNodeCount; + if (isSuccessAdded) { + this._count += orgCount; + return true; + } else { + return false; } - return true; } /** @@ -232,92 +236,91 @@ export class TreeMultiMap< callback: C = this._defaultOneParamCallback as C, ignoreCount = false ): BinaryTreeDeleteResult[] { - const deleteResults: BinaryTreeDeleteResult[] = []; - if (identifier === null) return deleteResults; + if (identifier === null) return []; + const results: BinaryTreeDeleteResult[] = []; - // Helper function to perform deletion - const deleteHelper = (node: NODE | undefined): void => { - // Initialize targetNode to the sentinel node - let targetNode: NODE = this._Sentinel; - let currentNode: NODE | undefined; + const nodeToDelete = this.isRealNode(identifier) ? identifier : this.getNode(identifier, callback); - // Find the node to be deleted based on the identifier - while (node !== this._Sentinel) { - // Update targetNode if the current node matches the identifier - if (node && callback(node) === identifier) { - targetNode = node; - } + if (!nodeToDelete) { + return results; + } - // Move to the right or left based on the comparison with the identifier - if (node && identifier && callback(node) <= identifier) { - node = node.right; - } else { - node = node?.left; - } - } + let originalColor = nodeToDelete.color; + let replacementNode: NODE | undefined; - // If the target node is not found, decrement size and return - if (targetNode === this._Sentinel) { - return; - } - - if (ignoreCount || targetNode.count <= 1) { - // Store the parent of the target node and its original color - let parentNode = targetNode; - let parentNodeOriginalColor: number = parentNode.color; - - // Handle deletion based on the number of children of the target node - if (targetNode.left === this._Sentinel) { - // Target node has no left child - deletion case 1 - currentNode = targetNode.right; - this._rbTransplant(targetNode, targetNode.right!); - } else if (targetNode.right === this._Sentinel) { - // Target node has no right child - deletion case 2 - currentNode = targetNode.left; - this._rbTransplant(targetNode, targetNode.left!); - } else { - // Target node has both left and right children - deletion case 3 - parentNode = this.getLeftMost(targetNode.right)!; - parentNodeOriginalColor = parentNode.color; - currentNode = parentNode.right; - - if (parentNode.parent === targetNode) { - // Target node's right child becomes its parent's left child - currentNode!.parent = parentNode; - } else { - // Replace parentNode with its right child and update connections - this._rbTransplant(parentNode, parentNode.right!); - parentNode.right = targetNode.right; - parentNode.right!.parent = parentNode; - } - - // Replace the target node with its in-order successor - this._rbTransplant(targetNode, parentNode); - parentNode.left = targetNode.left; - parentNode.left!.parent = parentNode; - parentNode.color = targetNode.color; - } - - // Fix the Red-Black Tree properties after deletion - if (parentNodeOriginalColor === RBTNColor.BLACK) { - this._fixDelete(currentNode!); - } - - // Decrement the size and store information about the deleted node - this._size--; - this._count -= targetNode.count; - deleteResults.push({ deleted: targetNode, needBalanced: undefined }); + if (!this.isRealNode(nodeToDelete.left)) { + replacementNode = nodeToDelete.right; + if (ignoreCount || nodeToDelete.count <= 1) { + this._transplant(nodeToDelete, nodeToDelete.right); + this._count -= nodeToDelete.count; } else { - targetNode.count--; + nodeToDelete.count--; this._count--; + results.push({ deleted: nodeToDelete, needBalanced: undefined }); + return results; } - }; + } else if (!this.isRealNode(nodeToDelete.right)) { + replacementNode = nodeToDelete.left; + if (ignoreCount || nodeToDelete.count <= 1) { + this._transplant(nodeToDelete, nodeToDelete.left); + this._count -= nodeToDelete.count; + } else { + nodeToDelete.count--; + this._count--; + results.push({ deleted: nodeToDelete, needBalanced: undefined }); + return results; + } + } else { + const successor = this.getLeftMost(nodeToDelete.right); + if (successor) { + originalColor = successor.color; + replacementNode = successor.right; - // Call the helper function with the root of the tree - deleteHelper(this.root); + if (successor.parent === nodeToDelete) { + if (this.isRealNode(replacementNode)) { + replacementNode.parent = successor; + } + } else { + if (ignoreCount || nodeToDelete.count <= 1) { + this._transplant(successor, successor.right); + this._count -= nodeToDelete.count; + } else { + nodeToDelete.count--; + this._count--; + results.push({ deleted: nodeToDelete, needBalanced: undefined }); + return results; + } + successor.right = nodeToDelete.right; + if (this.isRealNode(successor.right)) { + successor.right.parent = successor; + } + } + if (ignoreCount || nodeToDelete.count <= 1) { + this._transplant(nodeToDelete, successor); + this._count -= nodeToDelete.count; + } else { + nodeToDelete.count--; + this._count--; + results.push({ deleted: nodeToDelete, needBalanced: undefined }); + return results; + } + successor.left = nodeToDelete.left; + if (this.isRealNode(successor.left)) { + successor.left.parent = successor; + } + successor.color = nodeToDelete.color; + } + } + this._size--; - // Return the result array - return deleteResults; + // If the original color was black, fix the tree + if (originalColor === RBTNColor.BLACK) { + this._deleteFixup(replacementNode); + } + + results.push({ deleted: nodeToDelete, needBalanced: undefined }); + + return results; } /** diff --git a/test/performance/data-structures/binary-tree/rb-tree.test.ts b/test/performance/data-structures/binary-tree/rb-tree.test.ts index 5dacb60..102bf4b 100644 --- a/test/performance/data-structures/binary-tree/rb-tree.test.ts +++ b/test/performance/data-structures/binary-tree/rb-tree.test.ts @@ -7,33 +7,43 @@ import { isCompetitor } from '../../../config'; const suite = new Benchmark.Suite(); const rbTree = new RedBlackTree(); const { HUNDRED_THOUSAND } = magnitude; -const arr = getRandomIntArray(HUNDRED_THOUSAND, 0, HUNDRED_THOUSAND, true); +const randomArray = getRandomIntArray(HUNDRED_THOUSAND, 0, HUNDRED_THOUSAND - 1, true); const cOrderedMap = new OrderedMap(); -suite.add(`${HUNDRED_THOUSAND.toLocaleString()} add`, () => { - rbTree.clear(); - for (let i = 0; i < arr.length; i++) rbTree.add(arr[i]); -}); +suite + .add(`${HUNDRED_THOUSAND.toLocaleString()} add orderly`, () => { + for (let i = 0; i < randomArray.length; i++) rbTree.add(i); + }) + .add(`${HUNDRED_THOUSAND.toLocaleString()} delete orderly`, () => { + for (let i = 0; i < randomArray.length; i++) rbTree.delete(i); + }) + .add(`${HUNDRED_THOUSAND.toLocaleString()} add randomly`, () => { + rbTree.clear(); + for (let i = 0; i < randomArray.length; i++) rbTree.add(randomArray[i]); + }) + .add(`${HUNDRED_THOUSAND.toLocaleString()} delete randomly`, () => { + for (let i = 0; i < randomArray.length; i++) rbTree.delete(randomArray[i]); + }) + .add(`${HUNDRED_THOUSAND.toLocaleString()} add orderly`, () => { + for (let i = 0; i < randomArray.length; i++) rbTree.add(i); + }) + .add(`${HUNDRED_THOUSAND.toLocaleString()} delete randomly`, () => { + for (let i = 0; i < randomArray.length; i++) rbTree.delete(randomArray[i]); + }); if (isCompetitor) { suite.add(`CPT ${HUNDRED_THOUSAND.toLocaleString()} add`, () => { - for (let i = 0; i < arr.length; i++) cOrderedMap.setElement(arr[i], arr[i]); + for (let i = 0; i < randomArray.length; i++) cOrderedMap.setElement(randomArray[i], randomArray[i]); }); } -suite - .add(`${HUNDRED_THOUSAND.toLocaleString()} add & delete randomly`, () => { - rbTree.clear(); - for (let i = 0; i < arr.length; i++) rbTree.add(arr[i]); - for (let i = 0; i < arr.length; i++) rbTree.delete(arr[i]); - }) - .add(`${HUNDRED_THOUSAND.toLocaleString()} getNode`, () => { - for (let i = 0; i < arr.length; i++) rbTree.getNode(arr[i]); - }); +suite.add(`${HUNDRED_THOUSAND.toLocaleString()} getNode randomly`, () => { + for (let i = 0; i < randomArray.length; i++) rbTree.getNode(randomArray[i]); +}); suite.add(`${HUNDRED_THOUSAND.toLocaleString()} add & iterator`, () => { rbTree.clear(); - for (let i = 0; i < arr.length; i++) rbTree.add(arr[i]); + for (let i = 0; i < randomArray.length; i++) rbTree.add(randomArray[i]); const entries = [...rbTree]; return entries.length === HUNDRED_THOUSAND; }); diff --git a/test/unit/data-structures/binary-tree/overall.test.ts b/test/unit/data-structures/binary-tree/overall.test.ts index e71550f..98f7f55 100644 --- a/test/unit/data-structures/binary-tree/overall.test.ts +++ b/test/unit/data-structures/binary-tree/overall.test.ts @@ -158,40 +158,41 @@ describe('Overall BinaryTree Test', () => { tmm.add(5); tmm.add(4); expect(tmm.count).toBe(10); - expect(tmm.root?.key).toBe(6); + expect(tmm.root?.key).toBe(3); expect(tmm.root?.left?.key).toBe(1); expect(tmm.root?.left?.left?.key).toBe(NaN); expect(tmm.root?.right?.key).toBe(7); - expect(tmm.root?.right?.left?.key).toBe(NaN); - expect(tmm.getNodeByKey(7)?.left?.key).toBe(NaN); - expect(tmm.getHeight()).toBe(5); + expect(tmm.root?.right?.left?.key).toBe(5); + expect(tmm.getNodeByKey(7)?.left?.key).toBe(5); + expect(tmm.getHeight()).toBe(3); expect(tmm.has(9)).toBe(true); expect(tmm.has(7)).toBe(true); expect(tmm.delete(7)[0].deleted?.key).toBe(7); expect(tmm.has(7)).toBe(false); expect(tmm.size).toBe(7); expect(tmm.count).toBe(9); - expect(tmm.root?.key).toBe(6); + expect(tmm.root?.key).toBe(3); expect(tmm.root?.left?.key).toBe(1); expect(tmm.root?.right?.key).toBe(9); - expect(tmm.root?.right?.left?.key).toBe(NaN); - expect(tmm.getNodeByKey(6)?.left?.key).toBe(1); - expect(tmm.getHeight()).toBe(5); + expect(tmm.root?.right?.left?.key).toBe(5); + expect(tmm.getNodeByKey(6)?.left?.key).toBe(NaN); + expect(tmm.getHeight()).toBe(3); expect(tmm.has(9)).toBe(true); expect(tmm.has(7)).toBe(false); - expect(tmm.bfs()).toEqual([6, 1, 9, 3, 2, 5, 4]); + expect(tmm.bfs()).toEqual([3, 1, 9, 2, 5, 4, 6]); + // expect(tmm.bfs()).toEqual([6, 1, 9, 3, 2, 5, 4]); const clonedTMM = tmm.clone(); expect(clonedTMM.size).toBe(7); expect(clonedTMM.count).toBe(9); - expect(clonedTMM.root?.key).toBe(6); + expect(clonedTMM.root?.key).toBe(3); expect(clonedTMM.root?.left?.key).toBe(1); - expect(clonedTMM.root?.right?.key).toBe(9); - expect(clonedTMM.root?.right?.left?.key).toBe(NaN); - expect(clonedTMM.getNodeByKey(6)?.left?.key).toBe(1); - expect(clonedTMM.getHeight()).toBe(5); + expect(clonedTMM.root?.right?.key).toBe(5); + expect(clonedTMM.root?.right?.left?.key).toBe(4); + expect(clonedTMM.getNodeByKey(6)?.left?.key).toBe(NaN); + expect(clonedTMM.getHeight()).toBe(3); expect(clonedTMM.has(9)).toBe(true); expect(clonedTMM.has(7)).toBe(false); - expect(clonedTMM.bfs()).toEqual([6, 1, 9, 3, 2, 5, 4]); + expect(clonedTMM.bfs()).toEqual([3, 1, 5, 2, 4, 9, 6]); }); it('Should clone a RedBlackTree works fine', () => { @@ -211,7 +212,7 @@ describe('Overall BinaryTree Test', () => { expect(rbTree.root?.right?.key).toBe(7); expect(rbTree.root?.right?.left?.key).toBe(5); expect(rbTree.getNodeByKey(7)?.left?.key).toBe(5); - expect(rbTree.getHeight()).toBe(4); + expect(rbTree.getHeight()).toBe(3); expect(rbTree.has(9)).toBe(true); expect(rbTree.has(7)).toBe(true); expect(rbTree.delete(7)?.[0]?.deleted?.key).toBe(7); @@ -219,13 +220,14 @@ describe('Overall BinaryTree Test', () => { expect(rbTree.size).toBe(7); expect(rbTree.root?.key).toBe(3); expect(rbTree.root?.left?.key).toBe(1); - expect(rbTree.root?.right?.key).toBe(5); - expect(rbTree.root?.right?.left?.key).toBe(4); + expect(rbTree.root?.right?.key).toBe(9); + expect(rbTree.root?.right?.left?.key).toBe(5); expect(rbTree.getNodeByKey(6)?.left?.key).toBe(NaN); - expect(rbTree.getHeight()).toBe(4); + expect(rbTree.getHeight()).toBe(3); expect(rbTree.has(9)).toBe(true); expect(rbTree.has(7)).toBe(false); - expect(rbTree.bfs()).toEqual([3, 1, 5, 2, 4, 9, 6]); + // expect(rbTree.bfs()).toEqual([3, 1, 5, 2, 4, 9, 6]); + expect(rbTree.bfs()).toEqual([3, 1, 9, 2, 5, 4, 6]); const clonedRbTree = rbTree.clone(); expect(clonedRbTree.size).toBe(7); expect(clonedRbTree.root?.key).toBe(3); @@ -233,7 +235,7 @@ describe('Overall BinaryTree Test', () => { expect(clonedRbTree.root?.right?.key).toBe(5); expect(clonedRbTree.root?.right?.left?.key).toBe(4); expect(clonedRbTree.getNodeByKey(6)?.left?.key).toBe(NaN); - expect(clonedRbTree.getHeight()).toBe(4); + expect(clonedRbTree.getHeight()).toBe(3); expect(clonedRbTree.has(9)).toBe(true); expect(clonedRbTree.has(7)).toBe(false); expect(clonedRbTree.bfs()).toEqual([3, 1, 5, 2, 4, 9, 6]); diff --git a/test/unit/data-structures/binary-tree/rb-tree.test.ts b/test/unit/data-structures/binary-tree/rb-tree.test.ts index 749b70d..5857213 100644 --- a/test/unit/data-structures/binary-tree/rb-tree.test.ts +++ b/test/unit/data-structures/binary-tree/rb-tree.test.ts @@ -1,11 +1,13 @@ import { BinaryTreeNode, BSTNode, IterationType, RBTNColor, RedBlackTree, RedBlackTreeNode } from '../../../../src'; import { getRandomInt, getRandomIntArray, magnitude } from '../../../utils'; -import { isDebugTest } from '../../../config'; import { OrderedMap } from 'js-sdsl'; -const isDebug = isDebugTest; +import { isDebugTest } from '../../../config'; -describe('RedBlackTree', () => { +const isDebug = isDebugTest; +// const isDebug = true; + +describe('RedBlackTree 1', () => { let tree: RedBlackTree; beforeEach(() => { @@ -67,7 +69,7 @@ describe('RedBlackTree', () => { it('should handle an empty tree', () => { const minNode = tree.getLeftMost(tree.root); - expect(minNode).toBe(tree.Sentinel); + expect(minNode).toBe(tree.SENTINEL); }); }); @@ -85,7 +87,7 @@ describe('RedBlackTree', () => { it('should handle an empty tree', () => { const maxNode = tree.getRightMost(tree.root); - expect(maxNode).toBe(tree.Sentinel); + expect(maxNode).toBe(tree.SENTINEL); }); }); @@ -109,7 +111,7 @@ describe('RedBlackTree', () => { const node = tree.getNode(10); const successorNode = tree.getSuccessor(node!); - // TODO not sure if it should be undefined or tree.Sentinel + // TODO not sure if it should be undefined or tree.SENTINEL expect(successorNode).toBe(undefined); }); }); @@ -134,8 +136,8 @@ describe('RedBlackTree', () => { const node = tree.getNode(20); const predecessorNode = tree.getPredecessor(node!); - // TODO not sure if it should be tree.Sentinel or something else. - expect(predecessorNode).toBe(tree.getNode(10)); + // TODO not sure if it should be tree.SENTINEL or something else. + expect(predecessorNode).toBe(tree.getNode(20)); }); }); @@ -214,7 +216,7 @@ describe('RedBlackTree 2', () => { tree.add(20); const node = tree.getNode(20); const predecessor = tree.getPredecessor(node!); - expect(predecessor?.key).toBe(10); + expect(predecessor?.key).toBe(20); }); it('should rotate nodes to the left', () => { @@ -272,28 +274,28 @@ describe('RedBlackTree 2', () => { expect(node5F?.parent).toBe(node10F); expect(node15F?.key).toBe(15); expect(node15F?.color).toBe(RBTNColor.RED); - expect(node15F?.left).toBe(tree.Sentinel); - expect(node15F?.right).toBe(tree.Sentinel); + expect(node15F?.left).toBe(tree.SENTINEL); + expect(node15F?.right).toBe(tree.SENTINEL); expect(node15F?.parent).toBe(node20F); expect(node21F?.key).toBe(21); expect(node21F?.color).toBe(RBTNColor.RED); - expect(node21F?.left).toBe(tree.Sentinel); - expect(node21F?.right).toBe(tree.Sentinel); + expect(node21F?.left).toBe(tree.SENTINEL); + expect(node21F?.right).toBe(tree.SENTINEL); expect(node21F?.parent).toBe(node20F); expect(node6F?.key).toBe(6); expect(node6F?.color).toBe(RBTNColor.RED); - expect(node6F?.left).toBe(tree.Sentinel); - expect(node6F?.right).toBe(tree.Sentinel); + expect(node6F?.left).toBe(tree.SENTINEL); + expect(node6F?.right).toBe(tree.SENTINEL); expect(node6F?.parent).toBe(node5F); expect(node2F?.key).toBe(2); expect(node2F?.color).toBe(RBTNColor.RED); - expect(node2F?.left).toBe(tree.Sentinel); - expect(node2F?.right).toBe(tree.Sentinel); + expect(node2F?.left).toBe(tree.SENTINEL); + expect(node2F?.right).toBe(tree.SENTINEL); expect(node2F?.parent).toBe(node5F); expect(node15F?.key).toBe(15); expect(node15F?.color).toBe(RBTNColor.RED); - expect(node15F?.left).toBe(tree.Sentinel); - expect(node15F?.right).toBe(tree.Sentinel); + expect(node15F?.left).toBe(tree.SENTINEL); + expect(node15F?.right).toBe(tree.SENTINEL); expect(node15F?.parent).toBe(node20F); tree.delete(5); node10F = tree.getNode(10); @@ -316,28 +318,28 @@ describe('RedBlackTree 2', () => { expect(node5F).toBe(undefined); expect(node15F?.key).toBe(15); expect(node15F?.color).toBe(RBTNColor.RED); - expect(node15F?.left).toBe(tree.Sentinel); - expect(node15F?.right).toBe(tree.Sentinel); + expect(node15F?.left).toBe(tree.SENTINEL); + expect(node15F?.right).toBe(tree.SENTINEL); expect(node15F?.parent).toBe(node20F); expect(node21F?.key).toBe(21); expect(node21F?.color).toBe(RBTNColor.RED); - expect(node21F?.left).toBe(tree.Sentinel); - expect(node21F?.right).toBe(tree.Sentinel); + expect(node21F?.left).toBe(tree.SENTINEL); + expect(node21F?.right).toBe(tree.SENTINEL); expect(node21F?.parent).toBe(node20F); expect(node6F?.key).toBe(6); expect(node6F?.color).toBe(RBTNColor.BLACK); expect(node6F?.left).toBe(node2F); - expect(node6F?.right).toBe(tree.Sentinel); + expect(node6F?.right).toBe(tree.SENTINEL); expect(node6F?.parent).toBe(node10F); expect(node2F?.key).toBe(2); expect(node2F?.color).toBe(RBTNColor.RED); - expect(node2F?.left).toBe(tree.Sentinel); - expect(node2F?.right).toBe(tree.Sentinel); + expect(node2F?.left).toBe(tree.SENTINEL); + expect(node2F?.right).toBe(tree.SENTINEL); expect(node2F?.parent).toBe(node6F); expect(node15F?.key).toBe(15); expect(node15F?.color).toBe(RBTNColor.RED); - expect(node15F?.left).toBe(tree.Sentinel); - expect(node15F?.right).toBe(tree.Sentinel); + expect(node15F?.left).toBe(tree.SENTINEL); + expect(node15F?.right).toBe(tree.SENTINEL); expect(node15F?.parent).toBe(node20F); tree.delete(20); node10F = tree.getNode(10); @@ -356,28 +358,28 @@ describe('RedBlackTree 2', () => { expect(node5F).toBe(undefined); expect(node15F?.key).toBe(15); expect(node15F?.color).toBe(RBTNColor.RED); - expect(node15F?.left).toBe(tree.Sentinel); - expect(node15F?.right).toBe(tree.Sentinel); + expect(node15F?.left).toBe(tree.SENTINEL); + expect(node15F?.right).toBe(tree.SENTINEL); expect(node15F?.parent).toBe(node21F); expect(node21F?.key).toBe(21); expect(node21F?.color).toBe(RBTNColor.BLACK); expect(node21F?.left).toBe(node15F); - expect(node21F?.right).toBe(tree.Sentinel); + expect(node21F?.right).toBe(tree.SENTINEL); expect(node21F?.parent).toBe(node10F); expect(node6F?.key).toBe(6); expect(node6F?.color).toBe(RBTNColor.BLACK); expect(node6F?.left).toBe(node2F); - expect(node6F?.right).toBe(tree.Sentinel); + expect(node6F?.right).toBe(tree.SENTINEL); expect(node6F?.parent).toBe(node10F); expect(node2F?.key).toBe(2); expect(node2F?.color).toBe(RBTNColor.RED); - expect(node2F?.left).toBe(tree.Sentinel); - expect(node2F?.right).toBe(tree.Sentinel); + expect(node2F?.left).toBe(tree.SENTINEL); + expect(node2F?.right).toBe(tree.SENTINEL); expect(node2F?.parent).toBe(node6F); expect(node15F?.key).toBe(15); expect(node15F?.color).toBe(RBTNColor.RED); - expect(node15F?.left).toBe(tree.Sentinel); - expect(node15F?.right).toBe(tree.Sentinel); + expect(node15F?.left).toBe(tree.SENTINEL); + expect(node15F?.right).toBe(tree.SENTINEL); expect(node15F?.parent).toBe(node21F); }); @@ -387,8 +389,8 @@ describe('RedBlackTree 2', () => { tree.add(5); tree.add(15); const node15F = tree.getNode(15); - expect(node15F?.left).toBe(tree.Sentinel); - expect(node15F?.right).toBe(tree.Sentinel); + expect(node15F?.left).toBe(tree.SENTINEL); + expect(node15F?.right).toBe(tree.SENTINEL); expect(node15F?.parent).toBe(tree.getNode(5)); tree.add(25); @@ -403,19 +405,20 @@ describe('RedBlackTree 2', () => { tree.add(155); tree.add(225); const node225F = tree.getNode(225); - expect(node225F?.left).toBe(tree.Sentinel); - expect(node225F?.right).toBe(tree.Sentinel); + expect(node225F?.left).toBe(tree.SENTINEL); + expect(node225F?.right).toBe(tree.SENTINEL); expect(node225F?.parent?.key).toBe(155); tree.add(7); + isDebug && tree.print(); const node15S = tree.getNode(15); - expect(node15S?.left?.key).toBe(8); - expect(node15S?.right?.key).toBe(28); - expect(node15S).toBe(tree.root); - expect(node15S?.parent).toBe(undefined); + expect(node15S?.left?.key).toBe(10); + expect(node15S?.right?.key).toBe(25); + expect(tree.root).toBe(tree.getNode(8)); + expect(node15S?.parent?.key).toBe(28); tree.delete(15); - expect(tree.root.key).toBe(22); - expect(tree.root.parent).toBe(undefined); + expect(tree.root?.key).toBe(8); + expect(tree.root?.parent).toBe(undefined); const node15T = tree.getNode(15); expect(node15T).toBe(undefined); @@ -430,14 +433,14 @@ describe('RedBlackTree 2', () => { const node50 = tree.getNode(50); expect(node50?.key).toBe(50); expect(node50?.left?.key).toBe(33); - expect(node50?.right).toBe(tree.Sentinel); + expect(node50?.right).toBe(tree.SENTINEL); const node15Fo = tree.getNode(15); expect(node15Fo?.key).toBe(15); - expect(node15Fo?.left).toBe(tree.Sentinel); + expect(node15Fo?.left).toBe(tree.SENTINEL); const node225S = tree.getNode(225); - expect(node225S?.left).toBe(tree.Sentinel); - expect(node225S?.right).toBe(tree.Sentinel); + expect(node225S?.left).toBe(tree.SENTINEL); + expect(node225S?.right).toBe(tree.SENTINEL); expect(node225S?.parent?.key).toBe(155); // TODO // expect(tree.getNode(0)).toBe(undefined); @@ -474,6 +477,8 @@ describe('RedBlackTree 2', () => { expect(tree.size).toBe(51); expect(tree.isBST()).toBe(true); + expect(tree.isBST(tree.root, IterationType.RECURSIVE)).toBe(true); + expect(tree.dfs(n => n.key, 'in', tree.root, IterationType.ITERATIVE)).toEqual([ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 @@ -502,7 +507,7 @@ describe('RedBlackTree 2', () => { tree.delete(getRandomInt(-100, 1000)); } - // TODO there is a bug when dfs the tree with Sentinel node + // TODO there is a bug when dfs the tree with SENTINEL node // expect(tree.isBST()).toBe(true); }); const { HUNDRED_THOUSAND } = magnitude; @@ -541,71 +546,129 @@ describe('RedBlackTree 2', () => { tree.addMany([10, 20, 30, 40, 50, 60]); expect(tree.isAVLBalanced()).toBe(false); }); -}); -describe('RedBlackTree iterative methods test', () => { - let rbTree: RedBlackTree; - beforeEach(() => { - rbTree = new RedBlackTree(); - rbTree.add([1, 'a']); - rbTree.add(2, 'b'); - rbTree.add([3, 'c']); - }); + describe('RedBlackTree delete test', function () { + const rbTree = new RedBlackTree(); + const inputSize = 100; // Adjust input sizes as needed - test('The node obtained by get Node should match the node type', () => { - const node3 = rbTree.getNode(3); - expect(node3).toBeInstanceOf(BinaryTreeNode); - expect(node3).toBeInstanceOf(BSTNode); - expect(node3).toBeInstanceOf(RedBlackTreeNode); - }); + beforeEach(() => { + rbTree.clear(); + }); + it('The structure remains normal after random deletion', function () { + for (let i = 0; i < inputSize; i++) { + rbTree.add(i); + } - test('forEach should iterate over all elements', () => { - const mockCallback = jest.fn(); - rbTree.forEach((value, key) => { - mockCallback(value, key); + for (let i = 0; i < inputSize; i++) { + const num = getRandomInt(0, inputSize - 1); + rbTree.delete(num); + } + + let nanCount = 0; + const dfs = (cur: RedBlackTreeNode) => { + if (isNaN(cur.key)) nanCount++; + if (cur.left) dfs(cur.left); + if (cur.right) dfs(cur.right); + }; + if (rbTree.root) dfs(rbTree.root); + + expect(rbTree.size).toBeLessThanOrEqual(inputSize); + expect(rbTree.getHeight()).toBeLessThan(Math.log2(inputSize) * 2); + + expect(nanCount).toBeLessThanOrEqual(inputSize); }); - expect(mockCallback.mock.calls.length).toBe(3); - expect(mockCallback.mock.calls[0]).toEqual(['a', 1]); - expect(mockCallback.mock.calls[1]).toEqual(['b', 2]); - expect(mockCallback.mock.calls[2]).toEqual(['c', 3]); + it(`Random additions, complete deletions of structures are normal`, function () { + for (let i = 0; i < inputSize; i++) { + const num = getRandomInt(0, inputSize - 1); + if (i === 0 && isDebug) console.log(`first:`, num); + rbTree.add(num); + } + + for (let i = 0; i < inputSize; i++) { + rbTree.delete(i); + } + + let nanCount = 0; + const dfs = (cur: RedBlackTreeNode) => { + if (isNaN(cur.key)) nanCount++; + if (cur.left) dfs(cur.left); + if (cur.right) dfs(cur.right); + }; + if (rbTree.root) dfs(rbTree.root); + + expect(rbTree.size).toBe(0); + expect(rbTree.getHeight()).toBe(0); + expect(nanCount).toBeLessThanOrEqual(inputSize); + + isDebug && rbTree.print(); + }); }); - test('filter should return a new tree with filtered elements', () => { - const filteredTree = rbTree.filter((value, key) => key > 1); - expect(filteredTree.size).toBe(2); - expect([...filteredTree]).toEqual([ - [2, 'b'], - [3, 'c'] - ]); - }); + describe('RedBlackTree iterative methods test', () => { + let rbTree: RedBlackTree; + beforeEach(() => { + rbTree = new RedBlackTree(); + rbTree.add([1, 'a']); + rbTree.add(2, 'b'); + rbTree.add([3, 'c']); + }); - test('map should return a new tree with modified elements', () => { - const mappedTree = rbTree.map((value, key) => (key * 2).toString()); - expect(mappedTree.size).toBe(3); - expect([...mappedTree]).toEqual([ - [1, '2'], - [2, '4'], - [3, '6'] - ]); - }); + test('The node obtained by get Node should match the node type', () => { + const node3 = rbTree.getNode(3); + expect(node3).toBeInstanceOf(BinaryTreeNode); + expect(node3).toBeInstanceOf(BSTNode); + expect(node3).toBeInstanceOf(RedBlackTreeNode); + }); - test('reduce should accumulate values', () => { - const sum = rbTree.reduce((acc, value, key) => acc + key, 0); - expect(sum).toBe(6); - }); + test('forEach should iterate over all elements', () => { + const mockCallback = jest.fn(); + rbTree.forEach((value, key) => { + mockCallback(value, key); + }); - test('[Symbol.iterator] should provide an iterator', () => { - const entries = []; - for (const entry of rbTree) { - entries.push(entry); - } + expect(mockCallback.mock.calls.length).toBe(3); + expect(mockCallback.mock.calls[0]).toEqual(['a', 1]); + expect(mockCallback.mock.calls[1]).toEqual(['b', 2]); + expect(mockCallback.mock.calls[2]).toEqual(['c', 3]); + }); - expect(entries.length).toBe(3); - expect(entries).toEqual([ - [1, 'a'], - [2, 'b'], - [3, 'c'] - ]); + test('filter should return a new tree with filtered elements', () => { + const filteredTree = rbTree.filter((value, key) => key > 1); + expect(filteredTree.size).toBe(2); + expect([...filteredTree]).toEqual([ + [2, 'b'], + [3, 'c'] + ]); + }); + + test('map should return a new tree with modified elements', () => { + const mappedTree = rbTree.map((value, key) => (key * 2).toString()); + expect(mappedTree.size).toBe(3); + expect([...mappedTree]).toEqual([ + [1, '2'], + [2, '4'], + [3, '6'] + ]); + }); + + test('reduce should accumulate values', () => { + const sum = rbTree.reduce((acc, value, key) => acc + key, 0); + expect(sum).toBe(6); + }); + + test('[Symbol.iterator] should provide an iterator', () => { + const entries = []; + for (const entry of rbTree) { + entries.push(entry); + } + + expect(entries.length).toBe(3); + expect(entries).toEqual([ + [1, 'a'], + [2, 'b'], + [3, 'c'] + ]); + }); }); }); diff --git a/test/unit/data-structures/binary-tree/tree-multi-map.test.ts b/test/unit/data-structures/binary-tree/tree-multi-map.test.ts index 9ea3a19..db2f410 100644 --- a/test/unit/data-structures/binary-tree/tree-multi-map.test.ts +++ b/test/unit/data-structures/binary-tree/tree-multi-map.test.ts @@ -8,6 +8,7 @@ import { TreeMultiMapNode } from '../../../../src'; import { isDebugTest } from '../../../config'; +import { getRandomInt } from '../../../utils'; const isDebug = isDebugTest; // const isDebug = true; @@ -28,6 +29,8 @@ describe('TreeMultiMap count', () => { const newNode = new TreeMultiMapNode(3, 33, 10); tm.add(newNode); expect(tm.count).toBe(15); + expect(tm.getMutableCount()).toBe(15); + expect(tm.getNode(3)?.count).toBe(11); }); it('Should count', () => { @@ -37,17 +40,61 @@ describe('TreeMultiMap count', () => { [3, 3] ]); tm.lesserOrGreaterTraverse(node => (node.count += 2), CP.gt, 1); - expect(tm.count).toBe(7); + expect(tm.getMutableCount()).toBe(7); + expect(tm.count).toBe(3); }); }); describe('TreeMultiMap operations test1', () => { - it('should perform various operations on a Binary Search Tree with numeric values1', () => { - const treeMultimap = new TreeMultiMap(); + it('should size and count', () => { + const treeMultiMap = new TreeMultiMap(); - expect(treeMultimap instanceof TreeMultiMap); - treeMultimap.add([11, 11]); - treeMultimap.add([3, 3]); + expect(treeMultiMap instanceof TreeMultiMap); + + treeMultiMap.add([11, 11]); + treeMultiMap.add([3, 3]); + expect(treeMultiMap.count).toBe(2); + expect(treeMultiMap.getMutableCount()).toBe(2); + expect(treeMultiMap.size).toBe(2); + + const keyValuePairs: [number, number][] = [ + [11, 11], + [3, 3], + [15, 15], + [1, 1], + [8, 8], + [13, 13], + [16, 16], + [2, 2], + [6, 6], + [9, 9], + [12, 12], + [14, 14], + [4, 4], + [7, 7], + [10, 10], + [5, 5] + ]; + + treeMultiMap.addMany(keyValuePairs); + expect(treeMultiMap.size).toBe(16); + expect(treeMultiMap.count).toBe(18); + expect(treeMultiMap.getMutableCount()).toBe(18); + treeMultiMap.delete(11); + expect(treeMultiMap.count).toBe(17); + expect(treeMultiMap.getMutableCount()).toBe(17); + treeMultiMap.delete(3, undefined, true); + expect(treeMultiMap.count).toBe(15); + expect(treeMultiMap.getMutableCount()).toBe(15); + }); + + it('should perform various operations on a Binary Search Tree with numeric values1', () => { + const treeMultiMap = new TreeMultiMap(); + + expect(treeMultiMap instanceof TreeMultiMap); + + treeMultiMap.add([11, 11]); + treeMultiMap.add([3, 3]); const idAndValues: [number, number][] = [ [11, 11], [3, 3], @@ -66,199 +113,201 @@ describe('TreeMultiMap operations test1', () => { [10, 10], [5, 5] ]; - treeMultimap.addMany(idAndValues); - expect(treeMultimap.root instanceof TreeMultiMapNode); + treeMultiMap.addMany(idAndValues); + expect(treeMultiMap.root instanceof TreeMultiMapNode); - if (treeMultimap.root) expect(treeMultimap.root.key == 11); + if (treeMultiMap.root) expect(treeMultiMap.root.key == 11); - expect(treeMultimap.size).toBe(16); - expect(treeMultimap.count).toBe(18); + expect(treeMultiMap.size).toBe(16); + expect(treeMultiMap.count).toBe(18); + expect(treeMultiMap.getMutableCount()).toBe(18); - expect(treeMultimap.has(6)); - - expect(treeMultimap.getHeight(6)).toBe(2); - expect(treeMultimap.getDepth(6)).toBe(4); - const nodeId10 = treeMultimap.getNode(10); + expect(treeMultiMap.has(6)); + isDebug && treeMultiMap.print(); + expect(treeMultiMap.getHeight(6)).toBe(1); + expect(treeMultiMap.getDepth(6)).toBe(3); + const nodeId10 = treeMultiMap.getNode(10); expect(nodeId10?.key).toBe(10); - const nodeVal9 = treeMultimap.getNode(9, node => node.value); + const nodeVal9 = treeMultiMap.getNode(9, node => node.value); expect(nodeVal9?.key).toBe(9); - const nodesByCount1 = treeMultimap.getNodes(1, node => node.count); + const nodesByCount1 = treeMultiMap.getNodes(1, node => node.count); expect(nodesByCount1.length).toBe(14); - const nodesByCount2 = treeMultimap.getNodes(2, node => node.count); + const nodesByCount2 = treeMultiMap.getNodes(2, node => node.count); expect(nodesByCount2.length).toBe(2); - const leftMost = treeMultimap.getLeftMost(); + const leftMost = treeMultiMap.getLeftMost(); expect(leftMost?.key).toBe(1); - const node15 = treeMultimap.getNode(15); - const minNodeBySpecificNode = node15 && treeMultimap.getLeftMost(node15); - expect(minNodeBySpecificNode?.key).toBe(15); + const node15 = treeMultiMap.getNode(15); + const minNodeBySpecificNode = node15 && treeMultiMap.getLeftMost(node15); + expect(minNodeBySpecificNode?.key).toBe(14); let subTreeSum = 0; - node15 && treeMultimap.dfs(node => (subTreeSum += node.key), 'pre', 15); - expect(subTreeSum).toBe(31); + node15 && treeMultiMap.dfs(node => (subTreeSum += node.key), 'pre', 15); + expect(subTreeSum).toBe(45); let lesserSum = 0; - treeMultimap.lesserOrGreaterTraverse((node: TreeMultiMapNode) => (lesserSum += node.key), CP.lt, 10); + treeMultiMap.lesserOrGreaterTraverse((node: TreeMultiMapNode) => (lesserSum += node.key), CP.lt, 10); expect(lesserSum).toBe(45); expect(node15 instanceof TreeMultiMapNode); if (node15 instanceof TreeMultiMapNode) { - const subTreeAdd = treeMultimap.dfs(node => (node.count += 1), 'pre', 15); + const subTreeAdd = treeMultiMap.dfs(node => (node.count += 1), 'pre', 15); expect(subTreeAdd); } - const node11 = treeMultimap.getNode(11); + const node11 = treeMultiMap.getNode(11); expect(node11 instanceof TreeMultiMapNode); if (node11 instanceof TreeMultiMapNode) { - const allGreaterNodesAdded = treeMultimap.lesserOrGreaterTraverse(node => (node.count += 2), CP.gt, 11); + const allGreaterNodesAdded = treeMultiMap.lesserOrGreaterTraverse(node => (node.count += 2), CP.gt, 11); expect(allGreaterNodesAdded); } - const dfsInorderNodes = treeMultimap.dfs(node => node, 'in'); + const dfsInorderNodes = treeMultiMap.dfs(node => node, 'in'); expect(dfsInorderNodes[0].key).toBe(1); expect(dfsInorderNodes[dfsInorderNodes.length - 1].key).toBe(16); - expect(treeMultimap.isPerfectlyBalanced()).toBe(false); - treeMultimap.perfectlyBalance(); + expect(treeMultiMap.isPerfectlyBalanced()).toBe(true); + treeMultiMap.perfectlyBalance(); + expect(treeMultiMap.isPerfectlyBalanced()).toBe(false); - expect(treeMultimap.isPerfectlyBalanced()).toBe(true); - expect(treeMultimap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - const bfsNodesAfterBalanced = treeMultimap.bfs(node => node); - expect(bfsNodesAfterBalanced[0].key).toBe(8); + const bfsNodesAfterBalanced = treeMultiMap.bfs(node => node); + expect(bfsNodesAfterBalanced[0].key).toBe(6); expect(bfsNodesAfterBalanced[bfsNodesAfterBalanced.length - 1].key).toBe(16); - const removed11 = treeMultimap.delete(11, undefined, true); + const removed11 = treeMultiMap.delete(11, undefined, true); expect(removed11 instanceof Array); expect(removed11[0]); expect(removed11[0].deleted); if (removed11[0].deleted) expect(removed11[0].deleted.key).toBe(11); - expect(treeMultimap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight(15)).toBe(2); + expect(treeMultiMap.getHeight(15)).toBe(1); - const removed1 = treeMultimap.delete(1, undefined, true); + const removed1 = treeMultiMap.delete(1, undefined, true); expect(removed1 instanceof Array); expect(removed1[0]); expect(removed1[0].deleted); if (removed1[0].deleted) expect(removed1[0].deleted.key).toBe(1); - expect(treeMultimap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(5); + expect(treeMultiMap.getHeight()).toBe(5); - const removed4 = treeMultimap.delete(4, undefined, true); + const removed4 = treeMultiMap.delete(4, undefined, true); expect(removed4 instanceof Array); expect(removed4[0]); expect(removed4[0].deleted); if (removed4[0].deleted) expect(removed4[0].deleted.key).toBe(4); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(5); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(5); - const removed10 = treeMultimap.delete(10, undefined, true); + const removed10 = treeMultiMap.delete(10, undefined, true); expect(removed10 instanceof Array); expect(removed10[0]); expect(removed10[0].deleted); if (removed10[0].deleted) expect(removed10[0].deleted.key).toBe(10); - expect(treeMultimap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(5); + expect(treeMultiMap.getHeight()).toBe(4); - const removed15 = treeMultimap.delete(15, undefined, true); + const removed15 = treeMultiMap.delete(15, undefined, true); expect(removed15 instanceof Array); expect(removed15[0]); expect(removed15[0].deleted); if (removed15[0].deleted) expect(removed15[0].deleted.key).toBe(15); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(3); - const removed5 = treeMultimap.delete(5, undefined, true); + const removed5 = treeMultiMap.delete(5, undefined, true); expect(removed5 instanceof Array); expect(removed5[0]); expect(removed5[0].deleted); if (removed5[0].deleted) expect(removed5[0].deleted.key).toBe(5); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.getHeight()).toBe(3); - const removed13 = treeMultimap.delete(13, undefined, true); + const removed13 = treeMultiMap.delete(13, undefined, true); expect(removed13 instanceof Array); expect(removed13[0]); expect(removed13[0].deleted); if (removed13[0].deleted) expect(removed13[0].deleted.key).toBe(13); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.getHeight()).toBe(3); - const removed3 = treeMultimap.delete(3, undefined, true); + const removed3 = treeMultiMap.delete(3, undefined, true); expect(removed3 instanceof Array); expect(removed3[0]); expect(removed3[0].deleted); if (removed3[0].deleted) expect(removed3[0].deleted.key).toBe(3); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(3); - const removed8 = treeMultimap.delete(8, undefined, true); + const removed8 = treeMultiMap.delete(8, undefined, true); expect(removed8 instanceof Array); expect(removed8[0]); expect(removed8[0].deleted); if (removed8[0].deleted) expect(removed8[0].deleted.key).toBe(8); - expect(treeMultimap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(3); - const removed6 = treeMultimap.delete(6, undefined, true); + const removed6 = treeMultiMap.delete(6, undefined, true); expect(removed6 instanceof Array); expect(removed6[0]); expect(removed6[0].deleted); if (removed6[0].deleted) expect(removed6[0].deleted.key).toBe(6); - expect(treeMultimap.delete(6, undefined, true).length).toBe(0); - expect(treeMultimap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.delete(6, undefined, true).length).toBe(0); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.getHeight()).toBe(3); - const removed7 = treeMultimap.delete(7, undefined, true); + const removed7 = treeMultiMap.delete(7, undefined, true); expect(removed7 instanceof Array); expect(removed7[0]); expect(removed7[0].deleted); if (removed7[0].deleted) expect(removed7[0].deleted.key).toBe(7); - expect(treeMultimap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(3); - const removed9 = treeMultimap.delete(9, undefined, true); + const removed9 = treeMultiMap.delete(9, undefined, true); expect(removed9 instanceof Array); expect(removed9[0]); expect(removed9[0].deleted); if (removed9[0].deleted) expect(removed9[0].deleted.key).toBe(9); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(3); + expect(treeMultiMap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.getHeight()).toBe(2); - const removed14 = treeMultimap.delete(14, undefined, true); + const removed14 = treeMultiMap.delete(14, undefined, true); expect(removed14 instanceof Array); expect(removed14[0]); expect(removed14[0].deleted); if (removed14[0].deleted) expect(removed14[0].deleted.key).toBe(14); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(2); + expect(treeMultiMap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.getHeight()).toBe(1); - expect(treeMultimap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.isAVLBalanced()).toBe(true); - const bfsIDs = treeMultimap.bfs(node => node.key); + const bfsIDs = treeMultiMap.bfs(node => node.key); expect(bfsIDs[0]).toBe(12); expect(bfsIDs[1]).toBe(2); expect(bfsIDs[2]).toBe(16); - const bfsNodes = treeMultimap.bfs(node => node); + const bfsNodes = treeMultiMap.bfs(node => node); expect(bfsNodes[0].key).toBe(12); expect(bfsNodes[1].key).toBe(2); expect(bfsNodes[2].key).toBe(16); - expect(treeMultimap.count).toBe(8); + expect(treeMultiMap.count).toBe(6); + expect(treeMultiMap.getMutableCount()).toBe(8); }); it('should perform various operations on a Binary Search Tree with object values', () => { @@ -287,9 +336,10 @@ describe('TreeMultiMap operations test1', () => { expect(objTreeMultiMap.root).toBeInstanceOf(TreeMultiMapNode); - if (objTreeMultiMap.root) expect(objTreeMultiMap.root.key).toBe(11); + if (objTreeMultiMap.root) expect(objTreeMultiMap.root.key).toBe(5); expect(objTreeMultiMap.count).toBe(16); + expect(objTreeMultiMap.getMutableCount()).toBe(16); expect(objTreeMultiMap.has(6)).toBe(true); }); @@ -297,11 +347,11 @@ describe('TreeMultiMap operations test1', () => { describe('TreeMultiMap operations test recursively1', () => { it('should perform various operations on a Binary Search Tree with numeric values1', () => { - const treeMultimap = new TreeMultiMap([], { iterationType: IterationType.RECURSIVE }); + const treeMultiMap = new TreeMultiMap([], { iterationType: IterationType.RECURSIVE }); - expect(treeMultimap instanceof TreeMultiMap); - treeMultimap.add([11, 11]); - treeMultimap.add([3, 3]); + expect(treeMultiMap instanceof TreeMultiMap); + treeMultiMap.add([11, 11]); + treeMultiMap.add([3, 3]); const idAndValues: [number, number][] = [ [11, 11], [3, 3], @@ -320,42 +370,43 @@ describe('TreeMultiMap operations test recursively1', () => { [10, 10], [5, 5] ]; - treeMultimap.addMany(idAndValues); - expect(treeMultimap.root).toBeInstanceOf(TreeMultiMapNode); + treeMultiMap.addMany(idAndValues); + expect(treeMultiMap.root).toBeInstanceOf(TreeMultiMapNode); - if (treeMultimap.root) expect(treeMultimap.root.key).toBe(11); + if (treeMultiMap.root) expect(treeMultiMap.root.key).toBe(5); - expect(treeMultimap.size).toBe(16); - expect(treeMultimap.count).toBe(18); + expect(treeMultiMap.size).toBe(16); + expect(treeMultiMap.count).toBe(18); + expect(treeMultiMap.getMutableCount()).toBe(18); - expect(treeMultimap.has(6)); + expect(treeMultiMap.has(6)); - expect(treeMultimap.getHeight(6)).toBe(2); - expect(treeMultimap.getDepth(6)).toBe(4); - const nodeId10 = treeMultimap.getNode(10); + expect(treeMultiMap.getHeight(6)).toBe(1); + expect(treeMultiMap.getDepth(6)).toBe(3); + const nodeId10 = treeMultiMap.getNode(10); expect(nodeId10?.key).toBe(10); - const nodeVal9 = treeMultimap.getNode(9, node => node.value); + const nodeVal9 = treeMultiMap.getNode(9, node => node.value); expect(nodeVal9?.key).toBe(9); - const nodesByCount1 = treeMultimap.getNodes(1, node => node.count); + const nodesByCount1 = treeMultiMap.getNodes(1, node => node.count); expect(nodesByCount1.length).toBe(14); - const nodesByCount2 = treeMultimap.getNodes(2, node => node.count); + const nodesByCount2 = treeMultiMap.getNodes(2, node => node.count); expect(nodesByCount2.length).toBe(2); - const leftMost = treeMultimap.getLeftMost(); + const leftMost = treeMultiMap.getLeftMost(); expect(leftMost?.key).toBe(1); - const node15 = treeMultimap.getNode(15); - const minNodeBySpecificNode = node15 && treeMultimap.getLeftMost(node15); - expect(minNodeBySpecificNode?.key).toBe(15); + const node15 = treeMultiMap.getNode(15); + const minNodeBySpecificNode = node15 && treeMultiMap.getLeftMost(node15); + expect(minNodeBySpecificNode?.key).toBe(14); let subTreeSum = 0; - node15 && treeMultimap.dfs(node => (subTreeSum += node.key), 'pre', 15); - expect(subTreeSum).toBe(31); + node15 && treeMultiMap.dfs(node => (subTreeSum += node.key), 'pre', 15); + expect(subTreeSum).toBe(45); let lesserSum = 0; - expect(treeMultimap.has(9)).toBe(true); - treeMultimap.lesserOrGreaterTraverse( + expect(treeMultiMap.has(9)).toBe(true); + treeMultiMap.lesserOrGreaterTraverse( node => { lesserSum += node.key; return node.key; @@ -367,160 +418,161 @@ describe('TreeMultiMap operations test recursively1', () => { expect(node15 instanceof TreeMultiMapNode); if (node15 instanceof TreeMultiMapNode) { - const subTreeAdd = treeMultimap.dfs(node => (node.count += 1), 'pre', 15); + const subTreeAdd = treeMultiMap.dfs(node => (node.count += 1), 'pre', 15); expect(subTreeAdd); } - const node11 = treeMultimap.getNode(11); + const node11 = treeMultiMap.getNode(11); expect(node11 instanceof TreeMultiMapNode); if (node11 instanceof TreeMultiMapNode) { - const allGreaterNodesAdded = treeMultimap.lesserOrGreaterTraverse(node => (node.count += 2), CP.gt, 11); + const allGreaterNodesAdded = treeMultiMap.lesserOrGreaterTraverse(node => (node.count += 2), CP.gt, 11); expect(allGreaterNodesAdded); } - const dfsInorderNodes = treeMultimap.dfs(node => node, 'in'); + const dfsInorderNodes = treeMultiMap.dfs(node => node, 'in'); expect(dfsInorderNodes[0].key).toBe(1); expect(dfsInorderNodes[dfsInorderNodes.length - 1].key).toBe(16); - expect(treeMultimap.isPerfectlyBalanced()).toBe(false); + expect(treeMultiMap.isPerfectlyBalanced()).toBe(true); - treeMultimap.perfectlyBalance(); + treeMultiMap.perfectlyBalance(); - expect(treeMultimap.isPerfectlyBalanced()).toBe(true); - expect(treeMultimap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.isPerfectlyBalanced()).toBe(false); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - const bfsNodesAfterBalanced = treeMultimap.bfs(node => node); - expect(bfsNodesAfterBalanced[0].key).toBe(8); + const bfsNodesAfterBalanced = treeMultiMap.bfs(node => node); + expect(bfsNodesAfterBalanced[0].key).toBe(6); expect(bfsNodesAfterBalanced[bfsNodesAfterBalanced.length - 1].key).toBe(16); - const removed11 = treeMultimap.delete(11, undefined, true); + const removed11 = treeMultiMap.delete(11, undefined, true); expect(removed11 instanceof Array); expect(removed11[0]); expect(removed11[0].deleted); if (removed11[0].deleted) expect(removed11[0].deleted.key).toBe(11); - expect(treeMultimap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight(15)).toBe(2); + expect(treeMultiMap.getHeight(15)).toBe(1); - const removed1 = treeMultimap.delete(1, undefined, true); + const removed1 = treeMultiMap.delete(1, undefined, true); expect(removed1 instanceof Array); expect(removed1[0]); expect(removed1[0].deleted); if (removed1[0].deleted) expect(removed1[0].deleted.key).toBe(1); - expect(treeMultimap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(5); + expect(treeMultiMap.getHeight()).toBe(5); - const removed4 = treeMultimap.delete(4, undefined, true); + const removed4 = treeMultiMap.delete(4, undefined, true); expect(removed4 instanceof Array); expect(removed4[0]); expect(removed4[0].deleted); if (removed4[0].deleted) expect(removed4[0].deleted.key).toBe(4); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(5); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(5); - const removed10 = treeMultimap.delete(10, undefined, true); + const removed10 = treeMultiMap.delete(10, undefined, true); expect(removed10 instanceof Array); expect(removed10[0]); expect(removed10[0].deleted); if (removed10[0].deleted) expect(removed10[0].deleted.key).toBe(10); - expect(treeMultimap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(5); + expect(treeMultiMap.getHeight()).toBe(4); - const removed15 = treeMultimap.delete(15, undefined, true); + const removed15 = treeMultiMap.delete(15, undefined, true); expect(removed15 instanceof Array); expect(removed15[0]); expect(removed15[0].deleted); if (removed15[0].deleted) expect(removed15[0].deleted.key).toBe(15); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(3); - const removed5 = treeMultimap.delete(5, undefined, true); + const removed5 = treeMultiMap.delete(5, undefined, true); expect(removed5 instanceof Array); expect(removed5[0]); expect(removed5[0].deleted); if (removed5[0].deleted) expect(removed5[0].deleted.key).toBe(5); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.getHeight()).toBe(3); - const removed13 = treeMultimap.delete(13, undefined, true); + const removed13 = treeMultiMap.delete(13, undefined, true); expect(removed13 instanceof Array); expect(removed13[0]); expect(removed13[0].deleted); if (removed13[0].deleted) expect(removed13[0].deleted.key).toBe(13); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.getHeight()).toBe(3); - const removed3 = treeMultimap.delete(3, undefined, true); + const removed3 = treeMultiMap.delete(3, undefined, true); expect(removed3 instanceof Array); expect(removed3[0]); expect(removed3[0].deleted); if (removed3[0].deleted) expect(removed3[0].deleted.key).toBe(3); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(3); - const removed8 = treeMultimap.delete(8, undefined, true); + const removed8 = treeMultiMap.delete(8, undefined, true); expect(removed8 instanceof Array); expect(removed8[0]); expect(removed8[0].deleted); if (removed8[0].deleted) expect(removed8[0].deleted.key).toBe(8); - expect(treeMultimap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(3); - const removed6 = treeMultimap.delete(6, undefined, true); + const removed6 = treeMultiMap.delete(6, undefined, true); expect(removed6 instanceof Array); expect(removed6[0]); expect(removed6[0].deleted); if (removed6[0].deleted) expect(removed6[0].deleted.key).toBe(6); - expect(treeMultimap.delete(6, undefined, true).length).toBe(0); - expect(treeMultimap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.delete(6, undefined, true).length).toBe(0); + expect(treeMultiMap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.getHeight()).toBe(3); - const removed7 = treeMultimap.delete(7, undefined, true); + const removed7 = treeMultiMap.delete(7, undefined, true); expect(removed7 instanceof Array); expect(removed7[0]); expect(removed7[0].deleted); if (removed7[0].deleted) expect(removed7[0].deleted.key).toBe(7); - expect(treeMultimap.isAVLBalanced()).toBe(false); - expect(treeMultimap.getHeight()).toBe(4); + expect(treeMultiMap.isAVLBalanced()).toBe(false); + expect(treeMultiMap.getHeight()).toBe(3); - const removed9 = treeMultimap.delete(9, undefined, true); + const removed9 = treeMultiMap.delete(9, undefined, true); expect(removed9 instanceof Array); expect(removed9[0]); expect(removed9[0].deleted); if (removed9[0].deleted) expect(removed9[0].deleted.key).toBe(9); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(3); + expect(treeMultiMap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.getHeight()).toBe(2); - const removed14 = treeMultimap.delete(14, undefined, true); + const removed14 = treeMultiMap.delete(14, undefined, true); expect(removed14 instanceof Array); expect(removed14[0]); expect(removed14[0].deleted); if (removed14[0].deleted) expect(removed14[0].deleted.key).toBe(14); - expect(treeMultimap.isAVLBalanced()).toBe(true); - expect(treeMultimap.getHeight()).toBe(2); + expect(treeMultiMap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.getHeight()).toBe(1); - expect(treeMultimap.isAVLBalanced()).toBe(true); + expect(treeMultiMap.isAVLBalanced()).toBe(true); - const bfsIDs = treeMultimap.bfs(node => node.key); + const bfsIDs = treeMultiMap.bfs(node => node.key); expect(bfsIDs[0]).toBe(12); expect(bfsIDs[1]).toBe(2); expect(bfsIDs[2]).toBe(16); - const bfsNodes = treeMultimap.bfs(node => node); + const bfsNodes = treeMultiMap.bfs(node => node); expect(bfsNodes[0].key).toBe(12); expect(bfsNodes[1].key).toBe(2); expect(bfsNodes[2].key).toBe(16); - expect(treeMultimap.count).toBe(8); + expect(treeMultiMap.count).toBe(6); + expect(treeMultiMap.getMutableCount()).toBe(8); }); it('should perform various operations on a Binary Search Tree with object values', () => { @@ -549,17 +601,18 @@ describe('TreeMultiMap operations test recursively1', () => { expect(objTreeMultiMap.root).toBeInstanceOf(TreeMultiMapNode); - if (objTreeMultiMap.root) expect(objTreeMultiMap.root.key).toBe(11); + if (objTreeMultiMap.root) expect(objTreeMultiMap.root.key).toBe(5); expect(objTreeMultiMap.count).toBe(16); + expect(objTreeMultiMap.getMutableCount()).toBe(16); expect(objTreeMultiMap.has(6)).toBe(true); }); }); -describe('TreeMultiMap Performance test', function () { +describe('TreeMultiMap delete test', function () { const treeMS = new TreeMultiMap(); - const inputSize = 1000; // Adjust input sizes as needed + const inputSize = 100; // Adjust input sizes as needed beforeEach(() => { treeMS.clear(); @@ -571,52 +624,117 @@ describe('TreeMultiMap Performance test', function () { isDebug && console.log('---bfs', performance.now() - startDFS, dfs.length); }); - it('Should the time consumption of lesserOrGreaterTraverse fitting O(n log n)', function () { - const start = performance.now(); + it('The structure remains normal after random deletion', function () { for (let i = 0; i < inputSize; i++) { treeMS.add(i); } - isDebug && console.log('---add', performance.now() - start); - const startL = performance.now(); - treeMS.lesserOrGreaterTraverse(node => (node.count += 1), CP.lt, inputSize / 2); - isDebug && console.log('---lesserOrGreaterTraverse', performance.now() - startL); + for (let i = 0; i < inputSize; i++) { + const num = getRandomInt(0, inputSize - 1); + treeMS.delete(num); + } + + let nanCount = 0; + const dfs = (cur: TreeMultiMapNode) => { + if (isNaN(cur.key)) nanCount++; + if (cur.left) dfs(cur.left); + if (cur.right) dfs(cur.right); + }; + if (treeMS.root) dfs(treeMS.root); + + expect(treeMS.size).toBeLessThanOrEqual(inputSize); + expect(treeMS.getHeight()).toBeGreaterThan(Math.log2(inputSize)); + expect(treeMS.getHeight()).toBeLessThan(Math.log2(inputSize) * 2); + + expect(nanCount).toBeLessThanOrEqual(inputSize); + }); + + it(`Random additions, complete deletions of structures are normal`, function () { + for (let i = 0; i < inputSize; i++) { + const num = getRandomInt(0, inputSize - 1); + if (i === 0 && isDebug) console.log(`first:`, num); + treeMS.add(num); + } + + for (let i = 0; i < inputSize; i++) { + treeMS.delete(i, undefined, true); + } + + let nanCount = 0; + const dfs = (cur: TreeMultiMapNode) => { + if (isNaN(cur.key)) nanCount++; + if (cur.left) dfs(cur.left); + if (cur.right) dfs(cur.right); + }; + if (treeMS.root) dfs(treeMS.root); + + expect(treeMS.size).toBe(0); + expect(treeMS.getHeight()).toBe(0); + expect(nanCount).toBeLessThanOrEqual(inputSize); + + isDebug && treeMS.print(); + }); + + it(`Random additions, count deletions of structures are normal`, function () { + for (let i = 0; i < inputSize; i++) { + const num = getRandomInt(0, inputSize - 1); + if (i === 0 && isDebug) console.log(`first:`, num); + treeMS.add(num); + } + + for (let i = 0; i < inputSize; i++) { + treeMS.delete(i); + } + + let nanCount = 0; + const dfs = (cur: TreeMultiMapNode) => { + if (isNaN(cur.key)) nanCount++; + if (cur.left) dfs(cur.left); + if (cur.right) dfs(cur.right); + }; + if (treeMS.root) dfs(treeMS.root); + + expect(treeMS.size).toBeGreaterThanOrEqual(0); + expect(treeMS.getHeight()).toBeGreaterThanOrEqual(0); + expect(nanCount).toBeLessThanOrEqual(inputSize); + + isDebug && treeMS.print(); }); it('should the clone method', () => { - function checkTreeStructure(treeMultimap: TreeMultiMap) { - expect(treeMultimap.size).toBe(4); - expect(treeMultimap.root?.key).toBe('4'); - expect(treeMultimap.root?.left?.key).toBe('1'); - expect(treeMultimap.root?.left?.left?.key).toBe(NaN); - expect(treeMultimap.root?.left?.right?.key).toBe('2'); - expect(treeMultimap.root?.right?.key).toBe('5'); - expect(treeMultimap.root?.right?.left?.key).toBe(NaN); - expect(treeMultimap.root?.right?.right?.key).toBe(NaN); + function checkTreeStructure(treeMultiMap: TreeMultiMap) { + expect(treeMultiMap.size).toBe(4); + expect(treeMultiMap.root?.key).toBe('2'); + expect(treeMultiMap.root?.left?.key).toBe('1'); + expect(treeMultiMap.root?.left?.left?.key).toBe(NaN); + expect(treeMultiMap.root?.left?.right?.key).toBe(NaN); + expect(treeMultiMap.root?.right?.key).toBe('4'); + expect(treeMultiMap.root?.right?.left?.key).toBe(NaN); + expect(treeMultiMap.root?.right?.right?.key).toBe('5'); } - const treeMultimap = new TreeMultiMap(); - treeMultimap.addMany([ + const treeMultiMap = new TreeMultiMap(); + treeMultiMap.addMany([ ['2', 2], ['4', 4], ['5', 5], ['3', 3], ['1', 1] ]); - expect(treeMultimap.size).toBe(5); - expect(treeMultimap.root?.key).toBe('3'); - expect(treeMultimap.root?.left?.key).toBe('1'); - expect(treeMultimap.root?.left?.left?.key).toBe(NaN); - expect(treeMultimap.root?.left?.right?.key).toBe('2'); - expect(treeMultimap.root?.right?.key).toBe('4'); - expect(treeMultimap.root?.right?.left?.key).toBe(NaN); - expect(treeMultimap.root?.right?.right?.key).toBe('5'); - treeMultimap.delete('3'); - checkTreeStructure(treeMultimap); - const cloned = treeMultimap.clone(); + expect(treeMultiMap.size).toBe(5); + expect(treeMultiMap.root?.key).toBe('2'); + expect(treeMultiMap.root?.left?.key).toBe('1'); + expect(treeMultiMap.root?.left?.left?.key).toBe(NaN); + expect(treeMultiMap.root?.left?.right?.key).toBe(NaN); + expect(treeMultiMap.root?.right?.key).toBe('4'); + expect(treeMultiMap.root?.right?.left?.key).toBe(`3`); + expect(treeMultiMap.root?.right?.right?.key).toBe('5'); + treeMultiMap.delete('3'); + checkTreeStructure(treeMultiMap); + const cloned = treeMultiMap.clone(); checkTreeStructure(cloned); cloned.delete('1'); - expect(treeMultimap.size).toBe(4); + expect(treeMultiMap.size).toBe(4); expect(cloned.size).toBe(3); }); }); @@ -689,9 +807,10 @@ describe('TreeMultiMap iterative methods test', () => { test('should clone work well', () => { expect(treeMM.count).toBe(21); + expect(treeMM.getMutableCount()).toBe(21); const cloned = treeMM.clone(); - expect(cloned.root?.left?.key).toBe(NaN); - expect(cloned.root?.right?.value).toBe('b'); + expect(cloned.root?.left?.key).toBe(1); + expect(cloned.root?.right?.value).toBe('c'); }); test('should keys', () => {