[binary-tree] Provide comprehensive JSDoc comments for the enhanced APIs.

This commit is contained in:
Revone 2023-10-24 09:25:33 +08:00
parent 44c29d89fc
commit 74d4294320
8 changed files with 474 additions and 318 deletions

View file

@ -8,10 +8,12 @@ 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.37.0](https://github.com/zrwusa/data-structure-typed/compare/v1.35.0...main) (upcoming)
## [v1.37.3](https://github.com/zrwusa/data-structure-typed/compare/v1.35.0...main) (upcoming)
### Changes
- Optimization [`#23`](https://github.com/zrwusa/data-structure-typed/pull/23)
- Optimization [`#20`](https://github.com/zrwusa/data-structure-typed/pull/20)
- [binary-tree, graph] Replace all code that uses Arrays as makeshift Q… [`#18`](https://github.com/zrwusa/data-structure-typed/pull/18)
- 1. No need for dfsIterative; integrate it directly into the dfs metho… [`#17`](https://github.com/zrwusa/data-structure-typed/pull/17)
- [heap] fibonacci heap implemented. [test] big O estimate. [project] n… [`#15`](https://github.com/zrwusa/data-structure-typed/pull/15)

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "data-structure-typed",
"version": "1.37.2",
"version": "1.37.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "data-structure-typed",
"version": "1.37.2",
"version": "1.37.3",
"license": "MIT",
"devDependencies": {
"@types/benchmark": "^2.1.3",

View file

@ -1,6 +1,6 @@
{
"name": "data-structure-typed",
"version": "1.37.2",
"version": "1.37.3",
"description": "Data Structures of Javascript & TypeScript. Binary Tree, BST, Graph, Heap, Priority Queue, Linked List, Queue, Deque, Stack, AVL Tree, Tree Multiset, Trie, Directed Graph, Undirected Graph, Singly Linked List, Doubly Linked List, Max Heap, Max Priority Queue, Min Heap, Min Priority Queue.",
"main": "dist/index.js",
"module": "lib/index.js",

View file

@ -33,11 +33,12 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The `_swap` function swaps the location of two nodes in a binary tree.
* @param {N} srcNode - The source node that you want to _swap with the destination node.
* @param {N} destNode - The `destNode` parameter represents the destination node where the values from `srcNode` will
* be swapped to.
* @returns The `destNode` is being returned.
* The function swaps the key, value, and height properties between two nodes in a binary tree.
* @param {N} srcNode - The `srcNode` parameter represents the source node that needs to be swapped
* with the `destNode`.
* @param {N} destNode - The `destNode` parameter represents the destination node where the values
* from the source node (`srcNode`) will be swapped to.
* @returns The method is returning the `destNode` after swapping its properties with the `srcNode`.
*/
protected override _swap(srcNode: N, destNode: N): N {
const {key, val, height} = destNode;
@ -59,11 +60,12 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The function creates a new AVL tree node with the given key and value.
* @param {BinaryTreeNodeKey} key - The `key` parameter is the identifier for the binary tree node. It is used to uniquely
* identify each node in the tree.
* @param [val] - The `val` parameter is an optional value that can be assigned to the node. It represents the value
* that will be stored in the node.
* The function creates a new AVL tree node with the specified key and value.
* @param {BinaryTreeNodeKey} key - The key parameter is the key value that will be associated with
* the new node. It is used to determine the position of the node in the binary search tree.
* @param [val] - The parameter `val` is an optional value that can be assigned to the node. It is of
* type `N['val']`, which means it can be any value that is assignable to the `val` property of the
* node type `N`.
* @returns a new AVLTreeNode object with the specified key and value.
*/
override createNode(key: BinaryTreeNodeKey, val?: N['val']): N {
@ -71,11 +73,13 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The function overrides the add method of a binary tree node and balances the tree after inserting a new node.
* @param keyOrNode - The `keyOrNode` parameter is either a key or a node that needs to be added to the binary tree.
* @param [val] - The `val` parameter is an optional value that can be assigned to the node being added. It is of type
* `N['val']`, which means it should be of the same type as the `val` property of the nodes in the binary tree.
* @returns The method is returning the inserted node, or null or undefined if the insertion was not successful.
* The function overrides the add method of a binary tree node and balances the tree after inserting
* a new node.
* @param {BinaryTreeNodeKey | N | null} keyOrNode - The `keyOrNode` parameter can accept either a
* `BinaryTreeNodeKey` or a `N` (which represents a node in the binary tree) or `null`.
* @param [val] - The `val` parameter is the value that you want to assign to the new node that you
* are adding to the binary search tree.
* @returns The method is returning the inserted node (`N`), `null`, or `undefined`.
*/
override add(keyOrNode: BinaryTreeNodeKey | N | null, val?: N['val']): N | null | undefined {
// TODO support node as a param
@ -85,9 +89,11 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The function overrides the delete method of a binary tree and performs additional operations to balance the tree after deletion.
* The function overrides the delete method of a binary tree and balances the tree after deleting a
* node if necessary.
* @param {N | BinaryTreeNodeKey} nodeOrKey - The `nodeOrKey` parameter can be either a node object
* (`N`) or a key value (`BinaryTreeNodeKey`).
* @returns The method is returning an array of `BinaryTreeDeletedResult<N>` objects.
* @param nodeOrKey - The `nodeOrKey` parameter is either a node or a key that needs to be deleted from the binary tree.
*/
override delete(nodeOrKey: N | BinaryTreeNodeKey): BinaryTreeDeletedResult<N>[] {
const deletedResults = super.delete(nodeOrKey);
@ -100,10 +106,10 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The balance factor of a given AVL tree node is calculated by subtracting the height of its left subtree from the
* height of its right subtree.
* @param node - The parameter "node" is of type N, which represents a node in an AVL tree.
* @returns The balance factor of the given AVL tree node.
* The function calculates the balance factor of a node in a binary tree.
* @param {N} node - The parameter "node" represents a node in a binary tree data structure.
* @returns the balance factor of a given node. The balance factor is calculated by subtracting the
* height of the left subtree from the height of the right subtree.
*/
protected _balanceFactor(node: N): number {
if (!node.right)
@ -116,8 +122,9 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The function updates the height of a node in an AVL tree based on the heights of its left and right subtrees.
* @param node - The parameter `node` is an AVLTreeNode object, which represents a node in an AVL tree.
* The function updates the height of a node in a binary tree based on the heights of its left and
* right children.
* @param {N} node - The parameter "node" represents a node in a binary tree data structure.
*/
protected _updateHeight(node: N): void {
if (!node.left && !node.right) node.height = 0;
@ -129,9 +136,10 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The `_balancePath` function balances the AVL tree by performing appropriate rotations based on the balance factor of
* each node in the path from the given node to the root.
* @param node - The `node` parameter is an AVLTreeNode object, which represents a node in an AVL tree.
* The `_balancePath` function is used to update the heights of nodes and perform rotation operations
* to restore balance in an AVL tree after inserting a node.
* @param {N} node - The `node` parameter in the `_balancePath` function represents the node in the
* AVL tree that needs to be balanced.
*/
protected _balancePath(node: N): void {
const path = this.getPathToRoot(node, false); // first O(log n) + O(log n)
@ -173,8 +181,8 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The `_balanceLL` function performs a left-left rotation on an AVL tree to balance it.
* @param A - The parameter A is an AVLTreeNode object.
* The function `_balanceLL` performs a left-left rotation to balance a binary tree.
* @param {N} A - A is a node in a binary tree.
*/
protected _balanceLL(A: N): void {
const parentOfA = A.parent;
@ -203,8 +211,8 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The `_balanceLR` function performs a left-right rotation to balance an AVL tree.
* @param A - A is an AVLTreeNode object.
* The `_balanceLR` function performs a left-right rotation to balance a binary tree.
* @param {N} A - A is a node in a binary tree.
*/
protected _balanceLR(A: N): void {
const parentOfA = A.parent;
@ -251,8 +259,8 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The `_balanceRR` function performs a right-right rotation on an AVL tree to balance it.
* @param A - The parameter A is an AVLTreeNode object.
* The function `_balanceRR` performs a right-right rotation to balance a binary tree.
* @param {N} A - A is a node in a binary tree.
*/
protected _balanceRR(A: N): void {
const parentOfA = A.parent;
@ -286,8 +294,8 @@ export class AVLTree<N extends AVLTreeNode<N['val'], N> = AVLTreeNode> extends B
}
/**
* The `_balanceRL` function performs a right-left rotation to balance an AVL tree.
* @param A - A is an AVLTreeNode object.
* The function `_balanceRL` performs a right-left rotation to balance a binary tree.
* @param {N} A - A is a node in a binary tree.
*/
protected _balanceRL(A: N): void {
const parentOfA = A.parent;

View file

@ -20,29 +20,45 @@ import {IBinaryTree} from '../../interfaces';
import {trampoline} from '../../utils';
import {Queue} from '../queue';
/**
* Represents a node in a binary tree.
* @template V - The type of data stored in the node.
* @template FAMILY - The type of the family relationship in the binary tree.
*/
export class BinaryTreeNode<V = any, FAMILY extends BinaryTreeNode<V, FAMILY> = BinaryTreeNodeNested<V>> {
/**
* The constructor function initializes a BinaryTreeNode object with a key and an optional value.
* @param {BinaryTreeNodeKey} key - The `key` parameter is of type `BinaryTreeNodeKey` and represents the unique identifier
* of the binary tree node. It is used to distinguish one node from another in the binary tree.
* @param {V} [val] - The "val" parameter is an optional parameter of type V. It represents the value that will be
* stored in the binary tree node. If no value is provided, it will be set to undefined.
* Creates a new instance of BinaryTreeNode.
* @param {BinaryTreeNodeKey} key - The key associated with the node.
* @param {V} val - The value stored in the node.
*/
constructor(key: BinaryTreeNodeKey, val?: V) {
this.key = key;
this.val = val;
}
/**
* The key associated with the node.
*/
key: BinaryTreeNodeKey;
/**
* The value stored in the node.
*/
val: V | undefined;
private _left: FAMILY | null | undefined;
/**
* Get the left child node.
*/
get left(): FAMILY | null | undefined {
return this._left;
}
/**
* Set the left child node.
* @param {FAMILY | null | undefined} v - The left child node.
*/
set left(v: FAMILY | null | undefined) {
if (v) {
v.parent = this as unknown as FAMILY;
@ -52,10 +68,17 @@ export class BinaryTreeNode<V = any, FAMILY extends BinaryTreeNode<V, FAMILY> =
private _right: FAMILY | null | undefined;
/**
* Get the right child node.
*/
get right(): FAMILY | null | undefined {
return this._right;
}
/**
* Set the right child node.
* @param {FAMILY | null | undefined} v - The right child node.
*/
set right(v: FAMILY | null | undefined) {
if (v) {
v.parent = this as unknown as FAMILY;
@ -63,11 +86,14 @@ export class BinaryTreeNode<V = any, FAMILY extends BinaryTreeNode<V, FAMILY> =
this._right = v;
}
/**
* The parent node of the current node.
*/
parent: FAMILY | null | undefined;
/**
* The function determines the position of a node in a family tree structure.
* @returns a value of type `FamilyPosition`.
* Get the position of the node within its family.
* @returns {FamilyPosition} - The family position of the node.
*/
get familyPosition(): FamilyPosition {
const that = this as unknown as FAMILY;
@ -97,64 +123,75 @@ export class BinaryTreeNode<V = any, FAMILY extends BinaryTreeNode<V, FAMILY> =
}
}
/**
* Represents a binary tree data structure.
* @template N - The type of the binary tree's nodes.
*/
export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode> implements IBinaryTree<N> {
/**
* This is a constructor function for a binary tree class that takes an optional options parameter.
* @param {BinaryTreeOptions} [options] - The `options` parameter is an optional object that can be passed to the
* constructor of the `BinaryTree` class. It allows you to customize the behavior of the binary tree by providing
* different configuration options.
* Creates a new instance of BinaryTree.
* @param {BinaryTreeOptions} [options] - The options for the binary tree.
*/
constructor(options?: BinaryTreeOptions) {
if (options !== undefined) {
const {iterationType = IterationType.ITERATIVE} = options;
const { iterationType = IterationType.ITERATIVE } = options;
this._loopType = iterationType;
}
}
/**
* The function creates a new binary tree node with an optional value.
* @param {BinaryTreeNodeKey} key - The `key` parameter is the identifier for the binary tree node. It is of type
* `BinaryTreeNodeKey`, which represents the unique identifier for each node in the binary tree.
* @param [val] - The `val` parameter is an optional value that can be assigned to the node. It represents the value
* stored in the node.
* @returns a new instance of a BinaryTreeNode with the specified key and value.
* Creates a new instance of BinaryTreeNode with the given key and value.
* @param {BinaryTreeNodeKey} key - The key for the new node.
* @param {N['val']} val - The value for the new node.
* @returns {N} - The newly created BinaryTreeNode.
*/
createNode(key: BinaryTreeNodeKey, val?: N['val']): N {
return new BinaryTreeNode<N['val'], N>(key, val) as N;
}
// TODO placeholder node may need redesigned
private _root: N | null = null;
/**
* Get the root node of the binary tree.
*/
get root(): N | null {
return this._root;
}
private _size = 0;
/**
* Get the number of nodes in the binary tree.
*/
get size(): number {
return this._size;
}
private _loopType: IterationType = IterationType.ITERATIVE;
/**
* Get the iteration type used in the binary tree.
*/
get iterationType(): IterationType {
return this._loopType;
}
/**
* Set the iteration type for the binary tree.
* @param {IterationType} v - The new iteration type to set.
*/
set iterationType(v: IterationType) {
this._loopType = v;
}
/**
* The `_swap` function swaps the location of two nodes in a binary tree.
* @param {N} srcNode - The source node that you want to _swap with the destination node.
* @param {N} destNode - The `destNode` parameter represents the destination node where the values from `srcNode` will
* be swapped to.
* @returns The `destNode` is being returned.
* Swap the data of two nodes in the binary tree.
* @param {N} srcNode - The source node to swap.
* @param {N} destNode - The destination node to swap.
* @returns {N} - The destination node after the swap.
*/
protected _swap(srcNode: N, destNode: N): N {
const {key, val} = destNode;
const { key, val } = destNode;
const tempNode = this.createNode(key, val);
if (tempNode) {
@ -169,7 +206,7 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The clear() function resets the root, size, and maxKey properties to their initial values.
* Clear the binary tree, removing all nodes.
*/
clear() {
this._root = null;
@ -177,26 +214,18 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function checks if the size of an object is equal to zero and returns a boolean value.
* @returns A boolean value indicating whether the size of the object is 0 or not.
* Check if the binary tree is empty.
* @returns {boolean} - True if the binary tree is empty, false otherwise.
*/
isEmpty(): boolean {
return this.size === 0;
}
/**
* When all leaf nodes are null, it will no longer be possible to add new entity nodes to this binary tree.
* In this scenario, null nodes serve as "sentinel nodes," "virtual nodes," or "placeholder nodes."
*/
/**
* The `add` function adds a new node to a binary tree, either by ID or by creating a new node with a given value.
* @param {BinaryTreeNodeKey | N | null} keyOrNode - The `keyOrNode` parameter can be either a `BinaryTreeNodeKey`, which
* is a number representing the ID of a binary tree node, or it can be a `N` object, which represents a binary tree
* node itself. It can also be `null` if no node is specified.
* @param [val] - The `val` parameter is an optional value that can be assigned to the `val` property of the new node
* being added to the binary tree.
* @returns The function `add` returns either the inserted node (`N`), `null`, or `undefined`.
* Add a node with the given key and value to the binary tree.
* @param {BinaryTreeNodeKey | N | null} keyOrNode - The key or node to add to the binary tree.
* @param {N['val']} val - The value for the new node (optional).
* @returns {N | null | undefined} - The inserted node, or null if nothing was inserted, or undefined if the operation failed.
*/
add(keyOrNode: BinaryTreeNodeKey | N | null, val?: N['val']): N | null | undefined {
const _bfs = (root: N, newNode: N | null): N | undefined | null => {
@ -252,12 +281,12 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
* values, and adds them to the binary tree.
* @param {(BinaryTreeNodeKey | null)[] | (N | null)[]} keysOrNodes - An array of BinaryTreeNodeKey or BinaryTreeNode
* objects, or null values.
* @param {N['val'][]} [data] - The `data` parameter is an optional array of values (`N['val'][]`) that corresponds to
* the nodes or node IDs being added. It is used to set the value of each node being added. If `data` is not provided,
* @param {N['val'][]} [values] - The `values` parameter is an optional array of values (`N['val'][]`) that corresponds to
* the nodes or node IDs being added. It is used to set the value of each node being added. If `values` is not provided,
* the value of the nodes will be `undefined`.
* @returns The function `addMany` returns an array of `N`, `null`, or `undefined` values.
*/
addMany(keysOrNodes: (BinaryTreeNodeKey | null)[] | (N | null)[], data?: N['val'][]): (N | null | undefined)[] {
addMany(keysOrNodes: (BinaryTreeNodeKey | null)[] | (N | null)[], values?: N['val'][]): (N | null | undefined)[] {
// TODO not sure addMany not be run multi times
const inserted: (N | null | undefined)[] = [];
@ -273,7 +302,7 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
continue;
}
const val = data?.[i];
const val = values?.[i];
inserted.push(this.add(keyOrNode, val));
}
return inserted;
@ -293,12 +322,14 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
return keysOrNodes.length === this.addMany(keysOrNodes, data).length;
}
/**
* The `delete` function in TypeScript is used to delete a node from a binary search tree and returns an array of objects
* containing the deleted node and the node that needs to be balanced.
* @param {N | BinaryTreeNodeKey} nodeOrKey - The `nodeOrKey` parameter can be either a node object (`N`) or a binary tree
* node ID (`BinaryTreeNodeKey`).
* @returns The function `delete` returns an array of `BinaryTreeDeletedResult<N>` objects.
* The `delete` function removes a node from a binary search tree and returns the deleted node along
* with the parent node that needs to be balanced.
* @param {N | BinaryTreeNodeKey} nodeOrKey - The `nodeOrKey` parameter can be either a node (`N`) or
* a key (`BinaryTreeNodeKey`). If it is a key, the function will find the corresponding node in the
* binary tree.
* @returns an array of `BinaryTreeDeletedResult<N>` objects.
*/
delete(nodeOrKey: N | BinaryTreeNodeKey): BinaryTreeDeletedResult<N>[] {
const bstDeletedResult: BinaryTreeDeletedResult<N>[] = [];
@ -343,10 +374,16 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function calculates the depth of a node in a binary tree.
* @param {N | BinaryTreeNodeKey | null} distNode - The `distNode` parameter can be any node of the tree
* @param {N | BinaryTreeNodeKey | null} beginRoot - The `beginRoot` parameter can be the predecessor node of distNode
* @returns the depth of the given node or binary tree.
* The function `getDepth` calculates the depth of a given node in a binary tree relative to a
* specified root node.
* @param {N | BinaryTreeNodeKey | null} distNode - The `distNode` parameter represents the node
* whose depth we want to find in the binary tree. It can be either a node object (`N`), a key value
* of the node (`BinaryTreeNodeKey`), or `null`.
* @param {N | BinaryTreeNodeKey | null} beginRoot - The `beginRoot` parameter represents the
* starting node from which we want to calculate the depth. It can be either a node object or the key
* of a node in the binary tree. If no value is provided for `beginRoot`, it defaults to the root
* node of the binary tree.
* @returns the depth of the `distNode` relative to the `beginRoot`.
*/
getDepth(distNode: N | BinaryTreeNodeKey | null, beginRoot: N | BinaryTreeNodeKey | null = this.root): number {
if (typeof distNode === 'number') distNode = this.get(distNode);
@ -363,11 +400,15 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The `getHeight` function calculates the maximum height of a binary tree, either recursively or iteratively.
* @param {N | BinaryTreeNodeKey | null} [beginRoot] - The `beginRoot` parameter is optional and can be of type `N` (a
* generic type representing a node in a binary tree), `BinaryTreeNodeKey` (a type representing the ID of a binary tree
* node), or `null`.
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of
* The `getHeight` function calculates the maximum height of a binary tree using either recursive or
* iterative approach.
* @param {N | BinaryTreeNodeKey | null} beginRoot - The `beginRoot` parameter represents the
* starting node from which the height of the binary tree is calculated. It can be either a node
* object (`N`), a key value of a node in the tree (`BinaryTreeNodeKey`), or `null` if no starting
* node is specified. If `
* @param iterationType - The `iterationType` parameter is used to determine whether to calculate the
* height of the binary tree using a recursive approach or an iterative approach. It can have two
* possible values:
* @returns the height of the binary tree.
*/
getHeight(beginRoot: N | BinaryTreeNodeKey | null = this.root, iterationType = this.iterationType): number {
@ -412,13 +453,14 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
protected _defaultCallbackByKey: MapCallback<N> = node => node.key;
/**
* The `getMinHeight` function calculates the minimum height of a binary tree using either a recursive or iterative
* approach.
* @param {N | null} [beginRoot] - The `beginRoot` parameter is an optional parameter of type `N` or `null`. It
* represents the starting node from which to calculate the minimum height of a binary tree. If no value is provided
* for `beginRoot`, the `this.root` property is used as the default value.
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of loop
* @returns The function `getMinHeight` returns the minimum height of the binary tree.
* The `getMinHeight` function calculates the minimum height of a binary tree using either a
* recursive or iterative approach.
* @param {N | null} beginRoot - The `beginRoot` parameter is the starting node from which we want to
* calculate the minimum height of the tree. It is optional and defaults to the root of the tree if
* not provided.
* @param iterationType - The `iterationType` parameter is used to determine the method of iteration
* to calculate the minimum height of a binary tree. It can have two possible values:
* @returns The function `getMinHeight` returns the minimum height of a binary tree.
*/
getMinHeight(beginRoot: N | null = this.root, iterationType = this.iterationType): number {
if (!beginRoot) return -1;
@ -463,10 +505,10 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function checks if a binary tree is perfectly balanced by comparing the minimum height and the height of the
* tree.
* @param {N | null} [beginRoot] - The parameter `beginRoot` is of type `N` or `null`. It represents the root node of a
* tree or null if the tree is empty.
* The function checks if a binary tree is perfectly balanced by comparing the minimum height and the
* height of the tree.
* @param {N | null} beginRoot - The parameter `beginRoot` is of type `N | null`, which means it can
* either be of type `N` (representing a node in a tree) or `null` (representing an empty tree).
* @returns The method is returning a boolean value.
*/
isPerfectlyBalanced(beginRoot: N | null = this.root): boolean {
@ -474,17 +516,25 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function `getNodes` returns an array of nodes that match a given property name and value in a binary tree.
* @param callback
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeKey` or a
* generic type `N`. It represents the property of the binary tree node that you want to search for.
* specifies the property name to use when searching for nodes. If not provided, it defaults to 'key'.
* @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
* return only one node that matches the given `nodeProperty` or `propertyName`. If `onlyOne` is set to `true`, the
* function will stop traversing the tree and return the first matching node. If `only
* @param beginRoot
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of loop
* @returns an array of nodes (type N).
* The function `getNodes` returns an array of nodes that match a given node property, using either
* recursive or iterative traversal.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter is either a
* `BinaryTreeNodeKey` or a generic type `N`. It represents the property of the node that we are
* searching for. It can be a specific key value or any other property of the node.
* @param callback - The `callback` parameter is a function that takes a node as input and returns a
* value. This value is compared with the `nodeProperty` parameter to determine if the node should be
* included in the result. The `callback` parameter has a default value of
* `this._defaultCallbackByKey`, which
* @param [onlyOne=false] - A boolean value indicating whether to stop searching after finding the
* first node that matches the nodeProperty. If set to true, the function will return an array with
* only one element (or an empty array if no matching node is found). If set to false (default), the
* function will continue searching for all
* @param {N | null} beginRoot - The `beginRoot` parameter is the starting node from which the
* traversal of the binary tree will begin. It is optional and defaults to the root of the binary
* tree.
* @param iterationType - The `iterationType` parameter determines the type of iteration used to
* traverse the binary tree. It can have two possible values:
* @returns The function `getNodes` returns an array of nodes (`N[]`).
*/
getNodes(
nodeProperty: BinaryTreeNodeKey | N,
@ -528,13 +578,20 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function checks if a binary tree node has a specific property.
* @param callback - The `callback` parameter is a function that takes a node as a parameter and returns a value.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeKey` or `N`.
* It represents the property of the binary tree node that you want to check.
* specifies the name of the property to be checked in the nodes. If not provided, it defaults to 'key'.
* @param beginRoot - The `beginRoot` parameter is an optional parameter of type `N` or `null`. It represents the root node of a tree or null if the tree is empty.
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of loop
* The function checks if a binary tree has a node with a given property or key.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter is the key or value of
* the node that you want to find in the binary tree. It can be either a `BinaryTreeNodeKey` or a
* generic type `N`.
* @param callback - The `callback` parameter is a function that is used to determine whether a node
* matches the desired criteria. It takes a node as input and returns a boolean value indicating
* whether the node matches the criteria or not. The default callback function
* `this._defaultCallbackByKey` is used if no callback function is
* @param beginRoot - The `beginRoot` parameter is the starting point for the search. It specifies
* the node from which the search should begin. By default, it is set to `this.root`, which means the
* search will start from the root node of the binary tree. However, you can provide a different node
* as
* @param iterationType - The `iterationType` parameter specifies the type of iteration to be
* performed when searching for nodes in the binary tree. It can have one of the following values:
* @returns a boolean value.
*/
has(
@ -548,17 +605,19 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function returns the first node that matches the given property name and value, or null if no matching node is
* found.
* @param callback - The `callback` parameter is a function that takes a node as a parameter and returns a value.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeKey` or `N`.
* It represents the property of the binary tree node that you want to search for.
* specifies the property name to be used for searching the binary tree nodes. If this parameter is not provided, the
* default value is set to `'key'`.
* @param beginRoot - The `beginRoot` parameter is an optional parameter of type `N` or `null`. It represents the root node of a tree or null if the tree is empty.
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of loop used to traverse the binary tree.
* @returns either the value of the specified property of the node, or the node itself if no property name is provided.
* If no matching node is found, it returns null.
* The function `get` returns the first node in a binary tree that matches the given property or key.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter is the key or value of
* the node that you want to find in the binary tree. It can be either a `BinaryTreeNodeKey` or `N`
* type.
* @param callback - The `callback` parameter is a function that is used to determine whether a node
* matches the desired criteria. It takes a node as input and returns a boolean value indicating
* whether the node matches the criteria or not. The default callback function
* (`this._defaultCallbackByKey`) is used if no callback function is
* @param beginRoot - The `beginRoot` parameter is the starting point for the search. It specifies
* the root node from which the search should begin.
* @param iterationType - The `iterationType` parameter specifies the type of iteration to be
* performed when searching for a node in the binary tree. It can have one of the following values:
* @returns either the found node (of type N) or null if no node is found.
*/
get(
nodeProperty: BinaryTreeNodeKey | N,
@ -571,14 +630,14 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function `getPathToRoot` returns an array of nodes representing the path from a given node to the root node, with
* an option to reverse the order of the nodes.
* type that represents a node in your specific implementation.
* @param beginRoot - The `beginRoot` parameter is of type `N` and represents the starting node from which you want to
* @param {boolean} [isReverse=true] - The `isReverse` parameter is a boolean flag that determines whether the resulting
* path should be reversed or not. If `isReverse` is set to `true`, the path will be reversed before returning it. If
* `isReverse` is set to `false` or not provided, the path will
* @returns The function `getPathToRoot` returns an array of nodes (`N[]`).
* The function `getPathToRoot` returns an array of nodes starting from a given node and traversing
* up to the root node, with the option to reverse the order of the nodes.
* @param {N} beginRoot - The `beginRoot` parameter represents the starting node from which you want
* to find the path to the root node.
* @param [isReverse=true] - The `isReverse` parameter is a boolean flag that determines whether the
* resulting path should be reversed or not. If `isReverse` is set to `true`, the path will be
* reversed before returning it. If `isReverse` is set to `false` or not provided, the path will
* @returns The function `getPathToRoot` returns an array of type `N[]`.
*/
getPathToRoot(beginRoot: N, isReverse = true): N[] {
// TODO to support get path through passing key
@ -594,16 +653,15 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function `getLeftMost` returns the leftmost node in a binary tree, starting from a specified node or the root if
* no node is specified.
* @param {N | BinaryTreeNodeKey | null} [beginRoot] - The `beginRoot` parameter is optional and can be of type `N` (a
* generic type representing a node in a binary tree), `BinaryTreeNodeKey` (a type representing the ID of a binary tree
* node), or `null`.
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of loop used to traverse the binary tree.
* @returns The function `getLeftMost` returns the leftmost node in a binary tree. If the `beginRoot` parameter is
* provided, it starts the traversal from that node. If `beginRoot` is not provided or is `null`, it starts the traversal
* from the root of the binary tree. The function returns the leftmost node found during the traversal. If no leftmost
* node is found (
* The function `getLeftMost` returns the leftmost node in a binary tree, either using recursive or
* iterative traversal.
* @param {N | BinaryTreeNodeKey | null} beginRoot - The `beginRoot` parameter is the starting point
* for finding the leftmost node in a binary tree. It can be either a node object (`N`), a key value
* of a node (`BinaryTreeNodeKey`), or `null` if the tree is empty.
* @param iterationType - The `iterationType` parameter is used to determine the type of iteration to
* be performed when finding the leftmost node in a binary tree. It can have two possible values:
* @returns The function `getLeftMost` returns the leftmost node (`N`) in a binary tree. If there is
* no leftmost node, it returns `null`.
*/
getLeftMost(beginRoot: N | BinaryTreeNodeKey | null = this.root, iterationType = this.iterationType): N | null {
if (typeof beginRoot === 'number') beginRoot = this.get(beginRoot);
@ -629,15 +687,15 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The `getRightMost` function returns the rightmost node in a binary tree, either recursively or iteratively using tail
* recursion optimization.
* @param {N | null} [beginRoot] - The `node` parameter is an optional parameter of type `N` or `null`. It represents the
* starting node from which we want to find the rightmost node. If no node is provided, the function will default to
* using the root node of the data structure.
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of loop
* @returns The `getRightMost` function returns the rightmost node in a binary tree. If the `node` parameter is provided,
* it returns the rightmost node starting from that node. If the `node` parameter is not provided, it returns the
* rightmost node starting from the root of the binary tree.
* The function `getRightMost` returns the rightmost node in a binary tree, either recursively or
* iteratively.
* @param {N | null} beginRoot - The `beginRoot` parameter is the starting node from which we want to
* find the rightmost node. It is of type `N | null`, which means it can either be a node of type `N`
* or `null`. If it is `null`, it means there is no starting node
* @param iterationType - The `iterationType` parameter is used to determine the type of iteration to
* be performed when finding the rightmost node in a binary tree. It can have two possible values:
* @returns The function `getRightMost` returns the rightmost node (`N`) in a binary tree. If the
* `beginRoot` parameter is `null`, it returns `null`.
*/
getRightMost(beginRoot: N | null = this.root, iterationType = this.iterationType): N | null {
// TODO support get right most by passing key in
@ -662,10 +720,13 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function checks if a binary search tree is valid by traversing it either recursively or iteratively.
* @param {N | null} beginRoot - The `node` parameter represents the root node of a binary search tree (BST).
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of loop
* @returns a boolean value.
* The function `isSubtreeBST` checks if a given binary tree is a valid binary search tree.
* @param {N} beginRoot - The `beginRoot` parameter is the root node of the binary tree that you want
* to check if it is a binary search tree (BST) subtree.
* @param iterationType - The `iterationType` parameter is an optional parameter that specifies the
* type of iteration to use when checking if a subtree is a binary search tree (BST). It can have two
* possible values:
* @returns The function `isSubtreeBST` returns a boolean value.
*/
isSubtreeBST(beginRoot: N, iterationType = this.iterationType): boolean {
// TODO there is a bug
@ -698,8 +759,12 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function isBST checks if the binary tree is valid binary search tree.
* @returns The `isBST()` function is returning a boolean value.
* The function checks if a binary tree is a binary search tree.
* @param iterationType - The parameter "iterationType" is used to specify the type of iteration to
* be used when checking if the binary tree is a binary search tree (BST). It is an optional
* parameter with a default value of "this.iterationType". The value of "this.iterationType" is not
* provided in
* @returns a boolean value.
*/
isBST(iterationType = this.iterationType): boolean {
if (this.root === null) return true;
@ -707,13 +772,18 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function `subTreeTraverse` adds a delta value to a specified property of each node in a subtree.
* @param {N | BinaryTreeNodeKey | null} beginRoot - The `beginRoot` parameter represents the root node of a binary
* tree or the ID of a node in the binary tree. It can also be `null` if there is no subtree to add to.
* @param callback - The `callback` parameter is a function that takes a node as a parameter and returns a value.
* specifies the property of the binary tree node that should be modified. If not provided, it defaults to 'key'.
* @param iterationType - The `iterationType` parameter is an optional parameter of type `IterationType`. It represents the type of loop
* @returns a boolean value.
* The function `subTreeTraverse` traverses a binary tree and applies a callback function to each
* node, either recursively or iteratively.
* @param callback - The `callback` parameter is a function that will be called on each node in the
* subtree traversal. It takes a single argument, which is the current node being traversed, and
* returns a value. The return values from each callback invocation will be collected and returned as
* an array.
* @param {N | BinaryTreeNodeKey | null} beginRoot - The `beginRoot` parameter is the starting point
* for traversing the subtree. It can be either a node object, a key value of a node, or `null` to
* start from the root of the tree.
* @param iterationType - The `iterationType` parameter determines the type of traversal to be
* performed on the binary tree. It can have two possible values:
* @returns The function `subTreeTraverse` returns an array of `MapCallbackReturn<N>`.
*/
subTreeTraverse(
callback: MapCallback<N> = this._defaultCallbackByKey,
@ -748,13 +818,19 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The dfs function performs a depth-first search traversal on a binary tree and returns the accumulated properties of
* each node based on the specified pattern and property name.
* @param callback
* @param beginRoot - The `beginRoot` parameter is an optional parameter of type `N` or `null`. It represents the
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param iterationType - The type of loop to use for the depth-first search traversal. The default value is `IterationType.ITERATIVE`.
* @returns an instance of the BinaryTreeNodeProperties class, which contains the accumulated properties of the binary tree nodes based on the specified pattern and node or property name.
* The `dfs` function performs a depth-first search traversal on a binary tree, executing a callback
* function on each node according to a specified order pattern.
* @param callback - The `callback` parameter is a function that will be called on each node during
* the depth-first search traversal. It takes a node as input and returns a value. The default value
* is `this._defaultCallbackByKey`, which is a callback function defined elsewhere in the code.
* @param {DFSOrderPattern} [pattern=in] - The `pattern` parameter determines the order in which the
* nodes are visited during the depth-first search. There are three possible values for `pattern`:
* @param {N | null} beginRoot - The `beginRoot` parameter is the starting node for the depth-first
* search. It determines where the search will begin in the tree or graph structure. If `beginRoot`
* is `null`, an empty array will be returned.
* @param {IterationType} iterationType - The `iterationType` parameter determines the type of
* iteration used in the depth-first search algorithm. It can have two possible values:
* @returns The function `dfs` returns an array of `MapCallbackReturn<N>` values.
*/
dfs(
callback: MapCallback<N> = this._defaultCallbackByKey,
@ -830,11 +906,21 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
// --- start additional methods ---
/**
* The `listLevels` function collects nodes from a binary tree by a specified property and organizes them into levels.
* @param callback - The `callback` parameter is a function that takes a node and a level as parameters and returns a value.
* @param withLevel - The `withLevel` parameter is a boolean flag that determines whether to include the level of each node in the result. If `withLevel` is set to `true`, the function will include the level of each node in the result. If `withLevel` is set to `false` or not provided, the function will not include the level of each node in the result.
* @param beginRoot - The `beginRoot` parameter is an optional parameter of type `N` or `null`. It represents the root node of a tree or null if the tree is empty.
* @param iterationType
* The bfs function performs a breadth-first search traversal on a binary tree, executing a callback
* function on each node.
* @param callback - The `callback` parameter is a function that will be called for each node in the
* breadth-first search. It takes a node of type `N` as its argument and returns a value of type
* `BFSCallbackReturn<N>`. The default value for this parameter is `this._defaultCallbackByKey
* @param {boolean} [withLevel=false] - The `withLevel` parameter is a boolean flag that determines
* whether or not to include the level of each node in the callback function. If `withLevel` is set
* to `true`, the level of each node will be passed as an argument to the callback function. If
* `withLevel` is
* @param {N | null} beginRoot - The `beginRoot` parameter is the starting node for the breadth-first
* search. It determines from which node the search will begin. If `beginRoot` is `null`, the search
* will not be performed and an empty array will be returned.
* @param iterationType - The `iterationType` parameter determines the type of iteration to be used
* in the breadth-first search (BFS) algorithm. It can have two possible values:
* @returns The function `bfs` returns an array of `BFSCallbackReturn<N>[]`.
*/
bfs(
callback: BFSCallback<N> = this._defaultCallbackByKey,
@ -870,9 +956,9 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function returns the predecessor of a given node in a binary tree.
* @param node - The parameter `node` is a BinaryTreeNode object, representing a node in a binary tree.
* @returns the predecessor of the given node in a binary tree.
* The function returns the predecessor node of a given node in a binary tree.
* @param {N} node - The parameter "node" represents a node in a binary tree.
* @returns The function `getPredecessor` returns the predecessor node of the given node `node`.
*/
getPredecessor(node: N): N {
if (node.left) {
@ -891,17 +977,24 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
/**
* Time complexity is O(n)
* Space complexity of Iterative dfs equals to recursive dfs which is O(n) because of the stack
*/
/**
* The `morris` function performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris traversal algorithm.
* The Morris algorithm only modifies the tree's structure during traversal; once the traversal is complete,
* the tree's structure should be restored to its original state to maintain the tree's integrity.
* This is because the purpose of the Morris algorithm is to save space rather than permanently alter the tree's shape.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param callback - The `callback` parameter is a function that takes a node as a parameter and returns a value.
* @param beginRoot - The `beginRoot` parameter is an optional parameter of type `N` or `null`. It represents the
* @returns An array of BinaryTreeNodeProperties<N> objects.
*/
/**
* The `morris` function performs a depth-first traversal of a binary tree using the Morris traversal
* algorithm and returns an array of values obtained by applying a callback function to each node.
* @param callback - The `callback` parameter is a function that will be called on each node in the
* tree. It takes a node of type `N` as input and returns a value of type `MapCallbackReturn<N>`. The
* default value for this parameter is `this._defaultCallbackByKey`.
* @param {DFSOrderPattern} [pattern=in] - The `pattern` parameter in the `morris` function
* determines the order in which the nodes of a binary tree are traversed. It can have one of the
* following values:
* @param {N | null} beginRoot - The `beginRoot` parameter is the starting node for the Morris
* traversal. It specifies the root node of the tree from which the traversal should begin. If
* `beginRoot` is `null`, an empty array will be returned.
* @returns The `morris` function returns an array of `MapCallbackReturn<N>` values.
*/
morris(
callback: MapCallback<N> = this._defaultCallbackByKey,
@ -989,14 +1082,15 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function adds a new node to a binary tree if there is an available position.
* @param {N | null} newNode - The `newNode` parameter is of type `N | null`, which means it can either be a node of
* type `N` or `null`. It represents the node that you want to add to the binary tree.
* @param {N} parent - The parent parameter is of type N, which represents a node in a binary tree.
* @returns either the left or right child node of the parent node, depending on which child is available for adding
* the new node. If a new node is added, the function also updates the size of the binary tree. If neither the left nor
* right child is available, the function returns undefined. If the parent node is null, the function also returns
* undefined.
* The function `_addTo` adds a new node to a binary tree if there is an available position.
* @param {N | null} newNode - The `newNode` parameter represents the node that you want to add to
* the binary tree. It can be either a node object or `null`.
* @param {N} parent - The `parent` parameter represents the parent node to which the new node will
* be added as a child.
* @returns either the left or right child node of the parent node, depending on which child is
* available for adding the new node. If a new node is added, the function also updates the size of
* the binary tree. If neither the left nor right child is available, the function returns undefined.
* If the parent node is null, the function also returns undefined.
*/
protected _addTo(newNode: N | null, parent: N): N | null | undefined {
if (parent) {
@ -1023,9 +1117,10 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function sets the root property of an object to a given value, and if the value is not null, it also sets the
* parent property of the value to undefined.
* @param {N | null} v - The parameter `v` is of type `N | null`, which means it can either be of type `N` or `null`.
* The function sets the root property of an object to a given value, and if the value is not null,
* it also sets the parent property of the value to undefined.
* @param {N | null} v - The parameter `v` is of type `N | null`, which means it can either be of
* type `N` or `null`.
*/
protected _setRoot(v: N | null) {
if (v) {
@ -1035,8 +1130,9 @@ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode>
}
/**
* The function sets the size of a protected variable.
* @param {number} v - number
* The function sets the value of the protected property "_size" to the given number.
* @param {number} v - The parameter "v" is a number that represents the size value that we want to
* set.
*/
protected _setSize(v: number) {
this._size = v;

View file

@ -25,9 +25,12 @@ export class BSTNode<V = any, FAMILY extends BSTNode<V, FAMILY> = BSTNodeNested<
}
export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N> implements IBinaryTree<N> {
/**
* The constructor function initializes a binary search tree object with an optional comparator function.
* @param {BSTOptions} [options] - An optional object that contains configuration options for the binary search tree.
* The constructor function initializes a binary search tree object with an optional comparator
* function.
* @param {BSTOptions} [options] - An optional object that contains configuration options for the
* binary search tree.
*/
constructor(options?: BSTOptions) {
super(options);
@ -41,10 +44,10 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
/**
* The function creates a new binary search tree node with the given key and value.
* @param {BinaryTreeNodeKey} key - The `key` parameter is the identifier for the binary tree node. It is used to uniquely
* identify each node in the binary tree.
* @param [val] - The `val` parameter is an optional value that can be assigned to the node. It represents the value
* that will be stored in the node.
* @param {BinaryTreeNodeKey} key - The key parameter is the key value that will be associated with
* the new node. It is used to determine the position of the node in the binary search tree.
* @param [val] - The parameter `val` is an optional value that can be assigned to the node. It
* represents the value associated with the node in a binary search tree.
* @returns a new instance of the BSTNode class with the specified key and value.
*/
override createNode(key: BinaryTreeNodeKey, val?: N['val']): N {
@ -52,13 +55,14 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
}
/**
* The `add` function adds a new node to a binary search tree, either by creating a new node or by updating an existing
* node with the same ID.
* @param {BinaryTreeNodeKey | N | null} keyOrNode - The `keyOrNode` parameter can be either a `BinaryTreeNodeKey` or a `N`
* (which represents a binary tree node) or `null`.
* @param [val] - The `val` parameter is an optional value that can be assigned to the `val` property of the new node
* being added to the binary search tree.
* @returns The function `add` returns the inserted node (`inserted`) which can be of type `N`, `null`, or `undefined`.
* The `add` function in a binary search tree class inserts a new node with a given key and value
* into the tree.
* @param {BinaryTreeNodeKey | N | null} keyOrNode - The `keyOrNode` parameter can be either a
* `BinaryTreeNodeKey` (which can be a number or a string), a `BSTNode` object, or `null`.
* @param [val] - The `val` parameter is the value to be assigned to the new node being added to the
* binary search tree.
* @returns the inserted node (N) if it was successfully added to the binary search tree. If the node
* was not added or if the parameters were invalid, it returns null or undefined.
*/
override add(keyOrNode: BinaryTreeNodeKey | N | null, val?: N['val']): N | null | undefined {
// TODO support node as a parameter
@ -127,22 +131,20 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
}
/**
* The `addMany` function overrides the base class method to add multiple nodes to a binary search tree in a balanced
* manner.
* @param {[BinaryTreeNodeKey | N , N['val']][]} keysOrNodes - The `keysOrNodes` parameter in the `addMany` function is an array of
* `BinaryTreeNodeKey` or `N` (node) objects, or `null` values. It represents the nodes or node IDs that need to be added
* to the binary search tree.
* The `addMany` function is used to efficiently add multiple nodes to a binary search tree while
* maintaining balance.
* @param {[BinaryTreeNodeKey | N, N['val']][]} arr - The `arr` parameter in the `addMany` function
* represents an array of keys or nodes that need to be added to the binary search tree. It can be an
* array of `BinaryTreeNodeKey` or `N` (which represents the node type in the binary search tree) or
* `null
* @param {N['val'][]} data - The values of tree nodes
* @param {boolean} isBalanceAdd - If true the nodes will be balance inserted in binary search method.
* @param iterationType - The `iterationType` parameter is an optional parameter that specifies whether to use a
* @returns The function `addMany` returns an array of `N`, `null`, or `undefined` values.
* @param iterationType - The `iterationType` parameter determines the type of iteration to be used.
* It can have two possible values:
* @returns The `addMany` function returns an array of `N`, `null`, or `undefined` values.
*/
override addMany(
keysOrNodes: (BinaryTreeNodeKey | null)[] | (N | null)[],
data?: N['val'][],
isBalanceAdd = true,
iterationType = this.iterationType
): (N | null | undefined)[] {
override addMany(keysOrNodes: (BinaryTreeNodeKey | null)[] | (N | null)[], data?: N['val'][], isBalanceAdd = true, iterationType = this.iterationType): (N | null | undefined)[] {
// TODO this addMany function is inefficient, it should be optimized
function hasNoNull(arr: (BinaryTreeNodeKey | null)[] | (N | null)[]): arr is BinaryTreeNodeKey[] | N[] {
return arr.indexOf(null) === -1;
@ -211,22 +213,41 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
}
/**
* The function returns the first node in a binary tree that matches the given property name and value.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeKey` or a
* generic type `N`. It represents the property of the binary tree node that you want to search for.
* @param callback - The `callback` parameter is a function that takes a node as a parameter and returns a value.
* specifies the property name to use for searching the binary tree nodes. If not provided, it defaults to `'key'`.
* @returns The method is returning either a BinaryTreeNodeKey or N (generic type) or null.
* The function returns the first node in the binary tree that matches the given node property and
* callback.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter is used to specify the
* property of the binary tree node that you want to search for. It can be either a specific key
* value (`BinaryTreeNodeKey`) or a custom callback function (`MapCallback<N>`) that determines
* whether a node matches the desired property.
* @param callback - The `callback` parameter is a function that is used to determine whether a node
* matches the desired property. It takes a node as input and returns a boolean value indicating
* whether the node matches the property or not. If no callback function is provided, the default
* callback function `_defaultCallbackByKey` is used
* @param beginRoot - The `beginRoot` parameter is the starting point for the search. It specifies
* the root node from which the search should begin.
* @param iterationType - The `iterationType` parameter is used to specify the type of iteration to
* be performed when searching for nodes in the binary tree. It can have one of the following values:
* @returns either the first node that matches the given nodeProperty and callback, or null if no
* matching node is found.
*/
override get(nodeProperty: BinaryTreeNodeKey | N, callback: MapCallback<N> = this._defaultCallbackByKey): N | null {
return this.getNodes(nodeProperty, callback, true)[0] ?? null;
override get(nodeProperty: BinaryTreeNodeKey | N, callback: MapCallback<N> = this._defaultCallbackByKey,beginRoot = this.root, iterationType = this.iterationType): N | null {
return this.getNodes(nodeProperty, callback, true, beginRoot, iterationType)[0] ?? null;
}
/**
* lastKey returns the last key in a binary tree. If the binary tree is empty, it returns 0.
* @param beginRoot - The `beginRoot` parameter is an optional parameter that specifies the root node from which to begin
* the search for the last key.
* @param iterationType - The `iterationType` parameter is an optional parameter that specifies whether to use a recursive or iterative approach to search for the last key.
* The function `lastKey` returns the key of the rightmost node if the comparison result is less
* than, the key of the leftmost node if the comparison result is greater than, and the key of the
* rightmost node otherwise.
* @param {N | null} beginRoot - The `beginRoot` parameter is the starting point for finding the last
* key in a binary tree. It represents the root node of the subtree from which the search for the
* last key should begin. If no specific `beginRoot` is provided, the search will start from the root
* of the entire binary
* @param iterationType - The `iterationType` parameter is used to specify the type of iteration to
* be performed when finding the last key. It determines whether the iteration should be performed in
* pre-order, in-order, or post-order.
* @returns the key of the rightmost node in the binary tree if the comparison result is less than,
* the key of the leftmost node if the comparison result is greater than, and the key of the
* rightmost node otherwise. If no node is found, it returns 0.
*/
lastKey(beginRoot: N | null = this.root, iterationType = this.iterationType): BinaryTreeNodeKey {
if (this._compare(0, 1) === CP.lt) return this.getRightMost(beginRoot, iterationType)?.key ?? 0;
@ -235,17 +256,25 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
}
/**
* The function `getNodes` returns an array of nodes in a binary tree that match a given property value.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeKey` or an
* `N` type. It represents the property of the binary tree node that you want to compare with.
* @param callback - The `callback` parameter is a function that takes a node as a parameter and returns a value.
* specifies the property name to use for comparison. If not provided, it defaults to `'key'`.
* @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
* return only one node that matches the given `nodeProperty` or all nodes that match the `nodeProperty`. If `onlyOne`
* is set to `true`, the function will return an array with only one node (if
* @param beginRoot - The `beginRoot` parameter is an optional parameter that specifies the root node from which to
* @param iterationType
* @returns an array of nodes (type N).
* The function `getNodes` retrieves nodes from a binary tree based on a given node property or key,
* using either recursive or iterative traversal.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter represents the property
* of the binary tree node that you want to search for. It can be either a `BinaryTreeNodeKey` or a
* generic type `N`.
* @param callback - The `callback` parameter is a function that takes a node as input and returns a
* value. This value is compared with the `nodeProperty` parameter to determine if the node should be
* included in the result. The default value for `callback` is `this._defaultCallbackByKey`, which is
* a
* @param [onlyOne=false] - A boolean value indicating whether to stop the traversal after finding
* the first node that matches the nodeProperty. If set to true, the function will return an array
* containing only that node. If set to false (default), the function will continue the traversal and
* return an array containing all nodes that match the node
* @param {N | null} beginRoot - The `beginRoot` parameter is the starting node for the traversal. It
* specifies the root node of the binary tree from which the traversal should begin. If `beginRoot`
* is `null`, an empty array will be returned.
* @param iterationType - The `iterationType` parameter determines the type of iteration used to
* traverse the binary tree. It can have one of the following values:
* @returns an array of nodes (N[]).
*/
override getNodes(
nodeProperty: BinaryTreeNodeKey | N,
@ -305,13 +334,21 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
// --- start additional functions
/**
* The `lesserOrGreaterTraverse` function adds a delta value to the specified property of all nodes in a binary tree that
* have a greater value than a given node.
* @param callback - The `callback` parameter is a function that takes a node as a parameter and returns a value.
* represents the node in the binary tree to which the delta value will be added.
* @param lesserOrGreater - The `lesserOrGreater` parameter is an optional parameter that specifies whether the delta
* @param targetNode - The `targetNode` parameter is an optional parameter that specifies the node in the binary tree
* @param iterationType - The `iterationType` parameter is an optional parameter that specifies whether to use a
* The `lesserOrGreaterTraverse` function traverses a binary tree and applies a callback function to
* nodes that have a key value lesser or greater than a target key value.
* @param callback - The `callback` parameter is a function that will be called for each node that
* meets the condition specified by the `lesserOrGreater` parameter. It takes a node as an argument
* and returns a value.
* @param {CP} lesserOrGreater - The `lesserOrGreater` parameter is used to determine whether to
* traverse nodes that are lesser than, greater than, or equal to the `targetNode`. It can take one
* of the following values:
* @param {N | BinaryTreeNodeKey | null} targetNode - The `targetNode` parameter in the
* `lesserOrGreaterTraverse` function is used to specify the node from which the traversal should
* start. It can be either a reference to a specific node (`N`), the key of a node
* (`BinaryTreeNodeKey`), or `null` to
* @param iterationType - The `iterationType` parameter determines whether the traversal should be
* done recursively or iteratively. It can have two possible values:
* @returns The function `lesserOrGreaterTraverse` returns an array of `MapCallbackReturn<N>`.
*/
lesserOrGreaterTraverse(
callback: MapCallback<N> = this._defaultCallbackByKey,
@ -364,9 +401,12 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
*/
/**
* The `perfectlyBalance` function takes a binary tree, performs a depth-first search to sort the nodes, and then
* constructs a balanced binary search tree using either a recursive or iterative approach.
* @returns The function `perfectlyBalance()` returns a boolean value.
* The `perfectlyBalance` function balances a binary search tree by adding nodes in a way that
* ensures the tree is perfectly balanced.
* @param iterationType - The `iterationType` parameter is an optional parameter that specifies the
* type of iteration to use when building a balanced binary search tree. It can have two possible
* values:
* @returns The function `perfectlyBalance` returns a boolean value.
*/
perfectlyBalance(iterationType = this.iterationType): boolean {
const sorted = this.dfs(node => node, 'in'),
@ -406,7 +446,9 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
}
/**
* The function `isAVLBalanced` checks if a binary tree is balanced according to the AVL tree property.
* The function checks if a binary tree is AVL balanced using either recursive or iterative approach.
* @param iterationType - The `iterationType` parameter is used to determine the method of iteration
* to check if the AVL tree is balanced. It can have two possible values:
* @returns a boolean value.
*/
isAVLBalanced(iterationType = this.iterationType): boolean {
@ -456,12 +498,12 @@ export class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N>
protected _comparator: BSTComparator = (a, b) => a - b;
/**
* The function compares two binary tree node IDs using a comparator function and returns whether the first ID is
* greater than, less than, or equal to the second ID.
* @param {BinaryTreeNodeKey} a - "a" is a BinaryTreeNodeKey, which represents the identifier of a binary tree node.
* @param {BinaryTreeNodeKey} b - The parameter "b" in the above code refers to a BinaryTreeNodeKey.
* @returns a value of type CP (ComparisonResult). The possible return values are CP.gt (greater than), CP.lt (less
* than), or CP.eq (equal).
* The function compares two values using a comparator function and returns whether the first value
* is greater than, less than, or equal to the second value.
* @param {BinaryTreeNodeKey} a - The parameter "a" is of type BinaryTreeNodeKey.
* @param {BinaryTreeNodeKey} b - The parameter "b" in the above code represents a BinaryTreeNodeKey.
* @returns a value of type CP (ComparisonResult). The possible return values are CP.gt (greater
* than), CP.lt (less than), or CP.eq (equal).
*/
protected _compare(a: BinaryTreeNodeKey, b: BinaryTreeNodeKey): CP {
const compared = this._comparator(a, b);

View file

@ -69,11 +69,11 @@ export class TreeMultiset<N extends TreeMultisetNode<N['val'], N> = TreeMultiset
}
/**
* The function swaps the location of two nodes in a tree data structure.
* @param {N} srcNode - The source node that we want to _swap with the destination node.
* @param {N} destNode - The `destNode` parameter represents the destination node where the values from `srcNode` will
* be swapped with.
* @returns the `destNode` after swapping its values with the `srcNode`.
* The function swaps the values of two nodes in a binary tree.
* @param {N} srcNode - The source node that needs to be swapped with the destination node.
* @param {N} destNode - The `destNode` parameter represents the destination node where the values
* from `srcNode` will be swapped into.
* @returns The method is returning the `destNode` after swapping its properties with the `srcNode`.
*/
protected override _swap(srcNode: N, destNode: N): N {
const {key, val, count, height} = destNode;
@ -96,14 +96,17 @@ export class TreeMultiset<N extends TreeMultisetNode<N['val'], N> = TreeMultiset
}
/**
* The `add` function adds a new node to a binary search tree, maintaining the tree's properties and balancing if
* necessary.
* @param {BinaryTreeNodeKey | N} keyOrNode - The `keyOrNode` parameter can be either a `BinaryTreeNodeKey` or a `N` (which
* represents a `BinaryTreeNode`).
* @param [val] - The `val` parameter represents the value to be added to the binary tree node.
* @param {number} [count] - The `count` parameter is an optional parameter that specifies the number of times the
* value should be added to the binary tree. If the `count` parameter is not provided, it defaults to 1.
* @returns The method `add` returns either the inserted node (`N`), `null`, or `undefined`.
* The `add` function adds a new node to a binary search tree, updating the count if the key already
* exists, and balancing the tree if necessary.
* @param {BinaryTreeNodeKey | N | null} keyOrNode - The `keyOrNode` parameter can be either a
* `BinaryTreeNodeKey` (which represents the key of the node to be added), a `N` (which represents a
* node to be added), or `null` (which represents a null node).
* @param [val] - The `val` parameter represents the value associated with the key that is being
* added to the binary tree.
* @param [count=1] - The `count` parameter represents the number of occurrences of the key/value
* pair that will be added to the binary tree. It has a default value of 1, which means that if no
* count is specified, the default count will be 1.
* @returns The function `add` returns a value of type `N | null | undefined`.
*/
override add(keyOrNode: BinaryTreeNodeKey | N | null, val?: N['val'], count = 1): N | null | undefined {
let inserted: N | null | undefined = undefined,
@ -174,13 +177,12 @@ export class TreeMultiset<N extends TreeMultisetNode<N['val'], N> = TreeMultiset
}
/**
* The function adds a new node to a binary tree if there is an available slot on the left or right side of the parent
* node.
* @param {N | null} newNode - The `newNode` parameter represents the node that needs to be added to the tree. It can
* be either a node object (`N`) or `null`.
* @param {N} parent - The `parent` parameter represents the parent node to which the new node will be added as a
* child.
* @returns The method returns either the `parent.left`, `parent.right`, or `undefined`.
* The function adds a new node to a binary tree if there is an available slot in the parent node.
* @param {N | null} newNode - The `newNode` parameter represents the node that needs to be added to
* the tree. It can be either a node object (`N`) or `null`.
* @param {N} parent - The `parent` parameter represents the parent node to which the new node will
* be added as a child.
* @returns The method `_addTo` returns either the `parent.left`, `parent.right`, or `undefined`.
*/
override _addTo(newNode: N | null, parent: N): N | null | undefined {
if (parent) {
@ -208,13 +210,13 @@ export class TreeMultiset<N extends TreeMultisetNode<N['val'], N> = TreeMultiset
}
/**
* The `addMany` function takes an array of node IDs or nodes and adds them to the tree multiset, returning an array of
* the inserted nodes.
* @param {(BinaryTreeNodeKey | null)[] | (N | null)[]} keysOrNodes - An array of BinaryTreeNodeKey or BinaryTreeNode
* objects, or null values.
* @param {N['val'][]} [data] - The `data` parameter is an optional array of values (`N['val'][]`) that corresponds to
* the nodes being added. It is used when adding nodes using the `keyOrNode` and `data` arguments in the `this.add()`
* method. If provided, the `data` array should
* The `addMany` function adds multiple keys or nodes to a TreeMultiset and returns an array of the
* inserted nodes.
* @param {(BinaryTreeNodeKey | null)[] | (N | null)[]} keysOrNodes - An array of keys or nodes to be
* added to the multiset. Each element can be either a BinaryTreeNodeKey or a TreeMultisetNode.
* @param {N['val'][]} [data] - The `data` parameter is an optional array of values that correspond
* to the keys or nodes being added to the multiset. It is used to associate additional data with
* each key or node.
* @returns The function `addMany` returns an array of `N`, `null`, or `undefined` values.
*/
override addMany(
@ -242,9 +244,12 @@ export class TreeMultiset<N extends TreeMultisetNode<N['val'], N> = TreeMultiset
}
/**
* The `perfectlyBalance` function takes a binary tree, performs a depth-first search to sort the nodes, and then
* constructs a balanced binary search tree using either a recursive or iterative approach.
* @returns The function `perfectlyBalance()` returns a boolean value.
* The `perfectlyBalance` function in TypeScript takes a sorted array of nodes and builds a balanced
* binary search tree using either a recursive or iterative approach.
* @param iterationType - The `iterationType` parameter is an optional parameter that specifies the
* type of iteration to use when building a balanced binary search tree. It can have two possible
* values:
* @returns a boolean value.
*/
override perfectlyBalance(iterationType = this.iterationType): boolean {
const sorted = this.dfs(node => node, 'in'),
@ -285,13 +290,16 @@ export class TreeMultiset<N extends TreeMultisetNode<N['val'], N> = TreeMultiset
}
/**
* The `delete` function removes a node from a binary search tree and returns the deleted node along with the parent
* node that needs to be balanced.
* @param {N | BinaryTreeNodeKey | null} nodeOrKey - The `nodeOrKey` parameter can be one of the following:
* @param {boolean} [ignoreCount] - The `ignoreCount` parameter is an optional boolean parameter that determines
* whether to ignore the count of the node being removed. If `ignoreCount` is set to `true`, the count of the node will
* not be taken into account when removing it. If `ignoreCount` is set to `false
* @returns The function `delete` returns an array of `BinaryTreeDeletedResult<N>` objects.
* The `delete` function in a binary search tree deletes a node from the tree and returns the deleted
* node along with the parent node that needs to be balanced.
* @param {N | BinaryTreeNodeKey} nodeOrKey - The `nodeOrKey` parameter can be either a node object
* (`N`) or a key value (`BinaryTreeNodeKey`). It represents the node or key that needs to be deleted
* from the binary tree.
* @param [ignoreCount=false] - A boolean flag indicating whether to ignore the count of the node
* being deleted. If set to true, the count of the node will not be considered and the node will be
* deleted regardless of its count. If set to false (default), the count of the node will be
* decremented by 1 and
* @returns The method `delete` returns an array of `BinaryTreeDeletedResult<N>` objects.
*/
override delete(nodeOrKey: N | BinaryTreeNodeKey, ignoreCount = false): BinaryTreeDeletedResult<N>[] {
const bstDeletedResult: BinaryTreeDeletedResult<N>[] = [];
@ -350,7 +358,7 @@ export class TreeMultiset<N extends TreeMultisetNode<N['val'], N> = TreeMultiset
}
/**
* The clear() function clears the data and sets the count to 0.
* The clear() function clears the contents of a data structure and sets the count to zero.
*/
clear() {
super.clear();
@ -358,7 +366,7 @@ export class TreeMultiset<N extends TreeMultisetNode<N['val'], N> = TreeMultiset
}
/**
* The function "_setCount" is used to set the value of the "_count" property.
* The function sets the value of the "_count" property.
* @param {number} v - number
*/
protected _setCount(v: number) {

View file

@ -30,6 +30,6 @@ describe('LinkedList Performance Test', () => {
}
}
expect(doublyListPushCost).toBeLessThan(bigO.SQUARED * 5);
expect(doublyListPushCost).toBeLessThan(bigO.SQUARED * 10);
});
});