Socket
Socket
Sign inDemoInstall

data-structure-typed

Package Overview
Dependencies
Maintainers
1
Versions
201
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

data-structure-typed - npm Package Compare versions

Comparing version 1.37.0 to 1.37.1

2

package.json
{
"name": "data-structure-typed",
"version": "1.37.0",
"version": "1.37.1",
"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.",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -10,15 +10,15 @@ /**

import type {
BFSCallback,
BFSCallbackReturn,
BinaryTreeNodeKey,
BinaryTreeNodeNested,
BinaryTreeNodeProperties,
BinaryTreeNodeProperty,
BinaryTreeOptions
BinaryTreeOptions,
MapCallback,
MapCallbackReturn
} from '../../types';
import {
BinaryTreeDeletedResult,
BinaryTreeNodePropertyName,
DFSOrderPattern,
FamilyPosition,
LoopType,
NodeOrPropertyName
LoopType
} from '../../types';

@@ -131,2 +131,3 @@ import {IBinaryTree} from '../../interfaces';

}
// TODO placeholder node may need redesigned

@@ -155,8 +156,2 @@ private _root: N | null = null;

visitedKey: BinaryTreeNodeKey[] = [];
visitedVal: N['val'][] = [];
visitedNode: N[] = [];
/**

@@ -190,3 +185,2 @@ * The `_swap` function swaps the location of two nodes in a binary tree.

this._size = 0;
this._clearResults();
}

@@ -244,3 +238,3 @@

const existNode = keyOrNode ? this.get(keyOrNode, 'key') : undefined;
const existNode = keyOrNode ? this.get(keyOrNode, this._defaultCallbackByKey) : undefined;

@@ -368,4 +362,4 @@ if (this.root) {

getDepth(distNode: N | BinaryTreeNodeKey | null, beginRoot: N | BinaryTreeNodeKey | null = this.root): number {
if (typeof distNode === 'number') distNode = this.get(distNode, 'key');
if (typeof beginRoot === 'number') beginRoot = this.get(beginRoot, 'key');
if (typeof distNode === 'number') distNode = this.get(distNode);
if (typeof beginRoot === 'number') beginRoot = this.get(beginRoot);
let depth = 0;

@@ -390,3 +384,3 @@ while (distNode?.parent) {

getHeight(beginRoot: N | BinaryTreeNodeKey | null = this.root): number {
if (typeof beginRoot === 'number') beginRoot = this.get(beginRoot, 'key');
if (typeof beginRoot === 'number') beginRoot = this.get(beginRoot);
if (!beginRoot) return -1;

@@ -429,2 +423,4 @@

protected _defaultCallbackByKey: MapCallback<N> = node => node.key;
/**

@@ -493,5 +489,5 @@ * The `getMinHeight` function calculates the minimum height of a binary tree using either a recursive or iterative

* 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.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* specifies the property name to use when searching for nodes. If not provided, it defaults to 'key'.

@@ -501,2 +497,3 @@ * @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to

* function will stop traversing the tree and return the first matching node. If `only
* @param beginRoot
* @returns an array of nodes (type N).

@@ -506,12 +503,16 @@ */

nodeProperty: BinaryTreeNodeKey | N,
propertyName: BinaryTreeNodePropertyName = 'key',
onlyOne = false
callback: MapCallback<N> = this._defaultCallbackByKey,
onlyOne = false,
beginRoot: N | null = this.root
): N[] {
if (!this.root) return [];
if (!beginRoot) return [];
const result: N[] = [];
const ans: N[] = [];
if (this.loopType === LoopType.RECURSIVE) {
const _traverse = (cur: N) => {
if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return;
if (callback(cur) === nodeProperty) {
ans.push(cur);
if (onlyOne) return;
}
if (!cur.left && !cur.right) return;

@@ -522,9 +523,12 @@ cur.left && _traverse(cur.left);

_traverse(this.root);
_traverse(beginRoot);
} else {
const queue = new Queue<N>([this.root]);
const queue = new Queue<N>([beginRoot]);
while (queue.size > 0) {
const cur = queue.shift();
if (cur) {
if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return result;
if (callback(cur) === nodeProperty) {
ans.push(cur);
if (onlyOne) return ans;
}
cur.left && queue.push(cur.left);

@@ -536,3 +540,3 @@ cur.right && queue.push(cur.right);

return result;
return ans;
}

@@ -542,11 +546,11 @@

* 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.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* specifies the name of the property to be checked in the nodes. If not provided, it defaults to 'key'.
* @returns a boolean value.
*/
has(nodeProperty: BinaryTreeNodeKey | N, propertyName: BinaryTreeNodePropertyName = 'key'): boolean {
has(nodeProperty: BinaryTreeNodeKey | N, callback: MapCallback<N> = this._defaultCallbackByKey): boolean {
// TODO may support finding node by value equal
return this.getNodes(nodeProperty, propertyName).length > 0;
return this.getNodes(nodeProperty, callback, true).length > 0;
}

@@ -557,5 +561,5 @@

* 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.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* specifies the property name to be used for searching the binary tree nodes. If this parameter is not provided, the

@@ -566,5 +570,5 @@ * default value is set to `'key'`.

*/
get(nodeProperty: BinaryTreeNodeKey | N, propertyName: BinaryTreeNodePropertyName = 'key'): N | null {
get(nodeProperty: BinaryTreeNodeKey | N, callback: MapCallback<N> = this._defaultCallbackByKey): N | null {
// TODO may support finding node by value equal
return this.getNodes(nodeProperty, propertyName, true)[0] ?? null;
return this.getNodes(nodeProperty, callback, true)[0] ?? null;
}

@@ -575,4 +579,4 @@

* an option to reverse the order of the nodes.
* @param {N} node - The `node` parameter represents a node in a tree structure. It is of type `N`, which could be any
* 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

@@ -583,12 +587,12 @@ * path should be reversed or not. If `isReverse` is set to `true`, the path will be reversed before returning it. If

*/
getPathToRoot(node: N, isReverse = true): N[] {
getPathToRoot(beginRoot: N, isReverse = true): N[] {
// TODO to support get path through passing key
const result: N[] = [];
while (node.parent) {
while (beginRoot.parent) {
// Array.push + Array.reverse is more efficient than Array.unshift
// TODO may consider using Deque, so far this is not the performance bottleneck
result.push(node);
node = node.parent;
result.push(beginRoot);
beginRoot = beginRoot.parent;
}
result.push(node);
result.push(beginRoot);
return isReverse ? result.reverse() : result;

@@ -600,27 +604,2 @@ }

* no node is specified.
* generic type representing a node in a binary tree, `BinaryTreeNodeKey` (a type representing the ID of a binary tree
* node), or `null`.
* @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 (
*/
getLeftMost(): N | null;
/**
* 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} [node] - 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).
* @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 (
*/
getLeftMost(node: N): N;
/**
* 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

@@ -635,3 +614,3 @@ * generic type representing a node in a binary tree), `BinaryTreeNodeKey` (a type representing the ID of a binary tree

getLeftMost(beginRoot: N | BinaryTreeNodeKey | null = this.root): N | null {
if (typeof beginRoot === 'number') beginRoot = this.get(beginRoot, 'key');
if (typeof beginRoot === 'number') beginRoot = this.get(beginRoot);

@@ -661,24 +640,5 @@ if (!beginRoot) return beginRoot;

* recursion optimization.
* @returns The `getRightMost` function returns the rightmost node in a binary tree. It returns the
* rightmost node starting from the root of the binary tree.
*/
getRightMost(): N | null;
/**
* 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.
* @returns The `getRightMost` function returns the rightmost node in a binary tree. It returns the rightmost node
* starting from that node.
*/
getRightMost(beginRoot: N): N;
/**
* 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.
* @returns The `getRightMost` function returns the rightmost node in a binary tree. If the `node` parameter is provided,

@@ -754,37 +714,3 @@ * it returns the rightmost node starting from that node. If the `node` parameter is not provided, it returns the

/**
* The function calculates the size of a subtree by traversing it either recursively or iteratively.
* @param {N | null | undefined} subTreeRoot - The `subTreeRoot` parameter represents the root node of a subtree in a
* binary tree.
* @returns the size of the subtree rooted at `subTreeRoot`.
*/
getSubTreeSize(subTreeRoot: N | null | undefined) {
// TODO support key passed in
let size = 0;
if (!subTreeRoot) return size;
if (this._loopType === LoopType.RECURSIVE) {
const _traverse = (cur: N) => {
size++;
cur.left && _traverse(cur.left);
cur.right && _traverse(cur.right);
};
_traverse(subTreeRoot);
return size;
} else {
const stack: N[] = [subTreeRoot];
while (stack.length > 0) {
const cur = stack.pop()!;
size++;
cur.right && stack.push(cur.right);
cur.left && stack.push(cur.left);
}
return size;
}
}
/**
* The function `subTreeForeach` adds a delta value to a specified property of each node in a subtree.
* The function `subTreeTraverse` adds a delta value to a specified property of each node in a subtree.
* @param {N | BinaryTreeNodeKey | null} subTreeRoot - The `subTreeRoot` parameter represents the root node of a binary

@@ -796,10 +722,14 @@ * tree or the ID of a node in the binary tree. It can also be `null` if there is no subtree to add to.

*/
subTreeForeach(subTreeRoot: N | BinaryTreeNodeKey | null, callback: (node: N) => any): boolean {
if (typeof subTreeRoot === 'number') subTreeRoot = this.get(subTreeRoot, 'key');
subTreeTraverse(
callback: MapCallback<N> = this._defaultCallbackByKey,
subTreeRoot: N | BinaryTreeNodeKey | null = this.root
): MapCallbackReturn<N>[] {
if (typeof subTreeRoot === 'number') subTreeRoot = this.get(subTreeRoot);
if (!subTreeRoot) return false;
const ans: MapCallbackReturn<N>[] = [];
if (!subTreeRoot) return ans;
if (this._loopType === LoopType.RECURSIVE) {
const _traverse = (cur: N) => {
callback(cur);
ans.push(callback(cur));
cur.left && _traverse(cur.left);

@@ -816,3 +746,3 @@ cur.right && _traverse(cur.right);

callback(cur);
ans.push(callback(cur));
cur.right && stack.push(cur.right);

@@ -822,100 +752,11 @@ cur.left && stack.push(cur.left);

}
return true;
return ans;
}
/**
* Performs a breadth-first search (bfs) on a binary tree, accumulating properties of each node based on their 'key' property.
* @returns An array of binary tree node IDs.
*/
bfs(): BinaryTreeNodeKey[];
/**
* Performs a breadth-first search (bfs) on a binary tree, accumulating properties of each node based on the specified property name.
* @param {'key'} nodeOrPropertyName - The name of the property to accumulate.
* @returns An array of values corresponding to the specified property.
*/
bfs(nodeOrPropertyName: 'key'): BinaryTreeNodeKey[];
/**
* Performs a breadth-first search (bfs) on a binary tree, accumulating the 'val' property of each node.
* @param {'val'} nodeOrPropertyName - The name of the property to accumulate.
* @returns An array of 'val' properties from each node.
*/
bfs(nodeOrPropertyName: 'val'): N['val'][];
/**
* Performs a breadth-first search (bfs) on a binary tree, accumulating nodes themselves.
* @param {'node'} nodeOrPropertyName - The name of the property to accumulate.
* @returns An array of binary tree nodes.
*/
bfs(nodeOrPropertyName: 'node'): N[];
/**
* The bfs function performs a breadth-first search on a binary tree, accumulating properties of each node based on a specified property name.
* @param {NodeOrPropertyName} [nodeOrPropertyName] - An optional parameter that represents either a node or a property name.
* If a node is provided, the bfs algorithm will be performed starting from that node.
* If a property name is provided, the bfs algorithm will be performed starting from the root node, accumulating the specified property.
* @returns An instance of the `BinaryTreeNodeProperties` class with generic type `N`.
*/
bfs(nodeOrPropertyName: NodeOrPropertyName = 'key'): BinaryTreeNodeProperties<N> {
this._clearResults();
const queue = new Queue<N | null | undefined>([this.root]);
while (queue.size !== 0) {
const cur = queue.shift();
if (cur) {
this._accumulatedByPropertyName(cur, nodeOrPropertyName);
if (cur?.left !== null) queue.push(cur.left);
if (cur?.right !== null) queue.push(cur.right);
}
}
return this._getResultByPropertyName(nodeOrPropertyName);
}
/**
* Performs a depth-first search (dfs) traversal on a binary tree and accumulates properties of each node based on their 'key' property.
* @returns An array of binary tree node IDs.
*/
dfs(): BinaryTreeNodeKey[];
/**
* Performs a depth-first search (dfs) traversal on a binary tree and accumulates properties of each node based on the specified property name.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @returns An array of values corresponding to the specified property.
*/
dfs(pattern: DFSOrderPattern): BinaryTreeNodeKey[];
/**
* Performs a depth-first search (dfs) traversal on a binary tree and accumulates properties of each node based on the specified property name.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param {string} nodeOrPropertyName - The name of the property to accumulate.
* @param loopType - The type of loop to use for the depth-first search traversal. The default value is `LoopType.ITERATIVE`.
* @returns An array of values corresponding to the specified property.
*/
dfs(pattern: DFSOrderPattern, nodeOrPropertyName: 'key', loopType?: LoopType): BinaryTreeNodeKey[];
/**
* Performs a depth-first search (dfs) traversal on a binary tree and accumulates the 'val' property of each node.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param {'val'} nodeOrPropertyName - The name of the property to accumulate.
* @param loopType - The type of loop to use for the depth-first search traversal. The default value is `LoopType.ITERATIVE`.
* @returns An array of 'val' properties from each node.
*/
dfs(pattern: DFSOrderPattern, nodeOrPropertyName: 'val', loopType?: LoopType): N[];
/**
* Performs a depth-first search (dfs) traversal on a binary tree and accumulates nodes themselves.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param {'node'} nodeOrPropertyName - The name of the property to accumulate.
* @param loopType - The type of loop to use for the depth-first search traversal. The default value is `LoopType.ITERATIVE`.
* @returns An array of binary tree nodes.
*/
dfs(pattern: DFSOrderPattern, nodeOrPropertyName: 'node', loopType?: LoopType): N[];
/**
* 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 {NodeOrPropertyName} [nodeOrPropertyName] - The name of a property of the nodes in the binary tree. This property will be used to accumulate values during the depth-first search traversal. If no `nodeOrPropertyName` is provided, the default value is `'key'`.
* @param loopType - The type of loop to use for the depth-first search traversal. The default value is `LoopType.ITERATIVE`.

@@ -925,7 +766,9 @@ * @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.

dfs(
callback: MapCallback<N> = this._defaultCallbackByKey,
pattern: DFSOrderPattern = 'in',
nodeOrPropertyName: NodeOrPropertyName = 'key',
beginRoot: N | null = this.root,
loopType: LoopType = LoopType.ITERATIVE
): BinaryTreeNodeProperties<N> {
this._clearResults();
): MapCallbackReturn<N>[] {
if (!beginRoot) return [];
const ans: MapCallbackReturn<N>[] = [];
if (loopType === LoopType.RECURSIVE) {

@@ -936,7 +779,8 @@ const _traverse = (node: N) => {

if (node.left) _traverse(node.left);
this._accumulatedByPropertyName(node, nodeOrPropertyName);
ans.push(callback(node));
if (node.right) _traverse(node.right);
break;
case 'pre':
this._accumulatedByPropertyName(node, nodeOrPropertyName);
ans.push(callback(node));
if (node.left) _traverse(node.left);

@@ -948,3 +792,4 @@ if (node.right) _traverse(node.right);

if (node.right) _traverse(node.right);
this._accumulatedByPropertyName(node, nodeOrPropertyName);
ans.push(callback(node));
break;

@@ -954,7 +799,6 @@ }

this.root && _traverse(this.root);
_traverse(beginRoot);
} else {
if (!this.root) return this._getResultByPropertyName(nodeOrPropertyName);
// 0: visit, 1: print
const stack: {opt: 0 | 1; node: N | null | undefined}[] = [{opt: 0, node: this.root}];
const stack: {opt: 0 | 1; node: N | null | undefined}[] = [{opt: 0, node: beginRoot}];

@@ -965,3 +809,3 @@ while (stack.length > 0) {

if (cur.opt === 1) {
this._accumulatedByPropertyName(cur.node, nodeOrPropertyName);
ans.push(callback(cur.node));
} else {

@@ -994,3 +838,3 @@ switch (pattern) {

return this._getResultByPropertyName(nodeOrPropertyName);
return ans;
}

@@ -1001,73 +845,20 @@

/**
* Collects nodes from a binary tree by a specified property and organizes them into levels.
* @returns A 2D array of AbstractBinaryTreeNodeProperty<N> objects.
*/
listLevels(): BinaryTreeNodeKey[][];
/**
* Collects nodes from a binary tree by a specified property and organizes them into levels.
* @param {N | null} node - The root node of the binary tree or null. If null, the function will use the root node of the current binary tree instance.
* @returns A 2D array of AbstractBinaryTreeNodeProperty<N> objects.
*/
listLevels(node: N | null): BinaryTreeNodeKey[][];
/**
* Collects nodes from a binary tree by a specified property and organizes them into levels.
* @param {N | null} node - The root node of the binary tree or null. If null, the function will use the root node of the current binary tree instance.
* @param {'key} nodeOrPropertyName - The property of the BinaryTreeNode object to collect at each level.
* @returns A 2D array of values corresponding to the specified property.
*/
listLevels(node: N | null, nodeOrPropertyName: 'key'): BinaryTreeNodeKey[][];
/**
* Collects nodes from a binary tree by a specified property and organizes them into levels.
* @param {N | null} node - The root node of the binary tree or null. If null, the function will use the root node of the current binary tree instance.
* @param {'val'} nodeOrPropertyName - The property of the BinaryTreeNode object to collect at each level.
* @returns A 2D array of 'val' properties from each node.
*/
listLevels(node: N | null, nodeOrPropertyName: 'val'): N['val'][][];
/**
* Collects nodes from a binary tree by a specified property and organizes them into levels.
* @param {N | null} node - The root node of the binary tree or null. If null, the function will use the root node of the current binary tree instance.
* @param {'node'} nodeOrPropertyName - The property of the BinaryTreeNode object to collect at each level.
* @returns A 2D array of binary tree nodes.
*/
listLevels(node: N | null, nodeOrPropertyName: 'node'): N[][];
/**
* The `listLevels` function collects nodes from a binary tree by a specified property and organizes them into levels.
* @param {N | null} node - The `node` parameter is a BinaryTreeNode object or null. It represents the root node of a binary tree. If it is null, the function will use the root node of the current binary tree instance.
* @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is an optional parameter that specifies the property of the `BinaryTreeNode` object to collect at each level. It can be one of the following values: 'key', 'val', or 'node'. If not provided, it defaults to 'key'.
* @returns A 2D array of `AbstractBinaryTreeNodeProperty<N>` objects.
* @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.
*/
listLevels(
node: N | null = this.root,
nodeOrPropertyName: NodeOrPropertyName = 'key'
): BinaryTreeNodeProperty<N>[][] {
bfs(
callback: BFSCallback<N> = this._defaultCallbackByKey,
withLevel: boolean = false,
node?: N | null
): BFSCallbackReturn<N>[] {
if (!node) node = this.root;
if (!node) return [];
const levelsNodes: BinaryTreeNodeProperty<N>[][] = [];
const ans: BFSCallbackReturn<N>[] = [];
const collectByProperty = (node: N, level: number) => {
switch (nodeOrPropertyName) {
case 'key':
levelsNodes[level].push(node.key);
break;
case 'val':
levelsNodes[level].push(node.val);
break;
case 'node':
levelsNodes[level].push(node);
break;
default:
levelsNodes[level].push(node.key);
break;
}
};
if (this.loopType === LoopType.RECURSIVE) {
const _recursive = (node: N, level: number) => {
if (!levelsNodes[level]) levelsNodes[level] = [];
collectByProperty(node, level);
callback && ans.push(callback(node, withLevel ? level : undefined));
if (node.left) _recursive(node.left, level + 1);

@@ -1085,4 +876,3 @@ if (node.right) _recursive(node.right, level + 1);

if (!levelsNodes[level]) levelsNodes[level] = [];
collectByProperty(node, level);
callback && ans.push(callback(node, withLevel ? level : undefined));
if (node.right) stack.push([node.right, level + 1]);

@@ -1092,4 +882,3 @@ if (node.left) stack.push([node.left, level + 1]);

}
return levelsNodes;
return ans;
}

@@ -1122,49 +911,14 @@

/**
* Performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris traversal algorithm.
* @returns An array of binary tree node IDs.
*/
morris(): BinaryTreeNodeKey[];
/**
* Performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris traversal algorithm and accumulates properties of each node based on the specified property name.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param {'key'} nodeOrPropertyName - The name of the property to accumulate.
* @returns An array of values corresponding to the specified property.
*/
morris(pattern: DFSOrderPattern, nodeOrPropertyName: 'key'): BinaryTreeNodeKey[];
/**
* Performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris traversal algorithm and accumulates properties of each node based on the specified property name.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @returns An array of values corresponding to the specified property.
*/
morris(pattern: DFSOrderPattern): BinaryTreeNodeKey[];
/**
* Performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris traversal algorithm and accumulates the 'val' property of each node.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param {'val'} nodeOrPropertyName - The property of the BinaryTreeNode object to collect at each level.
* @returns An array of 'val' properties from each node.
*/
morris(pattern: DFSOrderPattern, nodeOrPropertyName: 'val'): N[];
/**
* Performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris traversal algorithm and accumulates nodes themselves.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param {'node'} nodeOrPropertyName - The property of the BinaryTreeNode object to collect at each level.
* @returns An array of binary tree nodes.
*/
morris(pattern: DFSOrderPattern, nodeOrPropertyName: 'node'): N[];
/**
* The `morris` function performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris traversal algorithm.
* @param {'in' | 'pre' | 'post'} [pattern] - The traversal pattern: 'in' (in-order), 'pre' (pre-order), or 'post' (post-order).
* @param {NodeOrPropertyName} [nodeOrPropertyName] - The property name of the nodes to retrieve or perform operations on during the traversal. It can be any valid property name of the nodes in the binary tree. If not provided, it defaults to 'key'.
* @param callback - The `callback` parameter is a function that takes a node as a parameter and returns a value.
* @returns An array of BinaryTreeNodeProperties<N> objects.
*/
morris(pattern: DFSOrderPattern = 'in', nodeOrPropertyName: NodeOrPropertyName = 'key'): BinaryTreeNodeProperties<N> {
morris(
callback: MapCallback<N> = this._defaultCallbackByKey,
pattern: DFSOrderPattern = 'in'
): MapCallbackReturn<N>[] {
if (this.root === null) return [];
const ans: MapCallbackReturn<N>[] = [];
this._clearResults();
let cur: N | null | undefined = this.root;

@@ -1186,3 +940,3 @@ const _reverseEdge = (node: N | null | undefined) => {

while (cur) {
this._accumulatedByPropertyName(cur, nodeOrPropertyName);
ans.push(callback(cur));
cur = cur.right;

@@ -1205,3 +959,3 @@ }

}
this._accumulatedByPropertyName(cur, nodeOrPropertyName);
ans.push(callback(cur));
cur = cur.right;

@@ -1216,3 +970,3 @@ }

predecessor.right = cur;
this._accumulatedByPropertyName(cur, nodeOrPropertyName);
ans.push(callback(cur));
cur = cur.left;

@@ -1224,3 +978,3 @@ continue;

} else {
this._accumulatedByPropertyName(cur, nodeOrPropertyName);
ans.push(callback(cur));
}

@@ -1248,4 +1002,3 @@ cur = cur.right;

}
return this._getResultByPropertyName(nodeOrPropertyName);
return ans;
}

@@ -1307,106 +1060,3 @@

/**
* The function `_clearResults` resets the values of several arrays used for tracking visited nodes and their
* properties.
*/
protected _clearResults() {
this.visitedKey = [];
this.visitedVal = [];
this.visitedNode = [];
}
/**
* The function checks if a given property of a binary tree node matches a specified value, and if so, adds the node to
* a result array.
* @param {N} cur - The current node being processed.
* @param {(N | null | undefined)[]} result - An array that stores the matching nodes.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter is either a `BinaryTreeNodeKey` or a `N`
* type. It represents the property value that we are comparing against in the switch statement.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* specifies the property name to compare against when pushing nodes into the `result` array. It can be either `'key'`
* or `'val'`. If it is not provided or is not equal to `'key'` or `'val'`, the
* @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
* stop after finding the first matching node or continue searching for all matching nodes. If `onlyOne` is set to
* `true`, the function will stop after finding the first matching node and return `true`. If `onlyOne
* @returns a boolean value indicating whether only one matching node should be pushed into the result array.
*/
protected _pushByPropertyNameStopOrNot(
cur: N,
result: (N | null | undefined)[],
nodeProperty: BinaryTreeNodeKey | N,
propertyName: BinaryTreeNodePropertyName = 'key',
onlyOne = false
) {
switch (propertyName) {
case 'key':
if (cur.key === nodeProperty) {
result.push(cur);
return onlyOne;
}
break;
case 'val':
if (cur.val === nodeProperty) {
result.push(cur);
return onlyOne;
}
break;
default:
if (cur.key === nodeProperty) {
result.push(cur);
return onlyOne;
}
break;
}
}
/**
* The function `_accumulatedByPropertyName` accumulates values from a given node based on the specified property name.
* @param {N} node - The `node` parameter is of type `N`, which represents a node in a data structure.
* @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is an optional parameter that
* can be either a string representing a property name or a reference to a `Node` object. If it is a string, it
* specifies the property name to be used for accumulating values. If it is a `Node` object, it specifies
*/
protected _accumulatedByPropertyName(node: N, nodeOrPropertyName: NodeOrPropertyName = 'key') {
switch (nodeOrPropertyName) {
case 'key':
this.visitedKey.push(node.key);
break;
case 'val':
this.visitedVal.push(node.val);
break;
case 'node':
this.visitedNode.push(node);
break;
default:
this.visitedKey.push(node.key);
break;
}
}
/**
* The time complexity of Morris traversal is O(n), it may slower than others
* The space complexity Morris traversal is O(1) because no using stack
*/
/**
* The function `_getResultByPropertyName` returns the corresponding property value based on the given node or property
* name.
* @param {NodeOrPropertyName} [nodeOrPropertyName] - The parameter `nodeOrPropertyName` is an optional parameter that
* can accept either a `NodeOrPropertyName` type or be undefined.
* @returns The method `_getResultByPropertyName` returns an instance of `BinaryTreeNodeProperties<N>`.
*/
protected _getResultByPropertyName(nodeOrPropertyName: NodeOrPropertyName = 'key'): BinaryTreeNodeProperties<N> {
switch (nodeOrPropertyName) {
case 'key':
return this.visitedKey;
case 'val':
return this.visitedVal;
case 'node':
return this.visitedNode;
default:
return this.visitedKey;
}
}
// --- end additional methods ---
}

@@ -10,6 +10,7 @@ /**

BinaryTreeNodeKey,
BinaryTreeNodePropertyName,
BSTComparator,
BSTNodeNested,
BSTOptions
BSTOptions,
MapCallback,
MapCallbackReturn
} from '../../types';

@@ -215,8 +216,8 @@ import {CP, LoopType} from '../../types';

* generic type `N`. It represents the property of the binary tree node that you want to search for.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* @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.
*/
override get(nodeProperty: BinaryTreeNodeKey | N, propertyName: BinaryTreeNodePropertyName = 'key'): N | null {
return this.getNodes(nodeProperty, propertyName, true)[0] ?? null;
override get(nodeProperty: BinaryTreeNodeKey | N, callback: MapCallback<N> = this._defaultCallbackByKey): N | null {
return this.getNodes(nodeProperty, callback, true)[0] ?? null;
}

@@ -241,3 +242,3 @@

* `N` type. It represents the property of the binary tree node that you want to compare with.
* @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
* @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'`.

@@ -247,2 +248,3 @@ * @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to

* 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
* @returns an array of nodes (type N).

@@ -252,14 +254,20 @@ */

nodeProperty: BinaryTreeNodeKey | N,
propertyName: BinaryTreeNodePropertyName = 'key',
onlyOne = false
callback: MapCallback<N> = this._defaultCallbackByKey,
onlyOne = false,
beginRoot: N | null = this.root
): N[] {
if (!this.root) return [];
const result: N[] = [];
if (!beginRoot) return [];
const ans: N[] = [];
if (this.loopType === LoopType.RECURSIVE) {
const _traverse = (cur: N) => {
if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return;
const callbackResult = callback(cur);
if (callbackResult === nodeProperty) {
ans.push(cur);
if (onlyOne) return;
}
if (!cur.left && !cur.right) return;
if (propertyName === 'key') {
// TODO potential bug
if (callback === this._defaultCallbackByKey) {
if (this._compare(cur.key, nodeProperty as number) === CP.gt) cur.left && _traverse(cur.left);

@@ -273,10 +281,15 @@ if (this._compare(cur.key, nodeProperty as number) === CP.lt) cur.right && _traverse(cur.right);

_traverse(this.root);
_traverse(beginRoot);
} else {
const queue = new Queue<N>([this.root]);
const queue = new Queue<N>([beginRoot]);
while (queue.size > 0) {
const cur = queue.shift();
if (cur) {
if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return result;
if (propertyName === 'key') {
const callbackResult = callback(cur);
if (callbackResult === nodeProperty) {
ans.push(cur);
if (onlyOne) return ans;
}
// TODO potential bug
if (callback === this._defaultCallbackByKey) {
if (this._compare(cur.key, nodeProperty as number) === CP.gt) cur.left && queue.push(cur.left);

@@ -292,3 +305,3 @@ if (this._compare(cur.key, nodeProperty as number) === CP.lt) cur.right && queue.push(cur.right);

return result;
return ans;
}

@@ -299,16 +312,17 @@

/**
* The `lesserOrGreaterForeach` function adds a delta value to the specified property of all nodes in a binary tree that
* 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.
* @param {N | BinaryTreeNodeKey | null} node - The `node` parameter can be either of type `N` (a generic type), `BinaryTreeNodeKey`, or `null`. It
* 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 callback - The `callback` parameter is a function that takes a node as a parameter and returns a boolean
*/
lesserOrGreaterForeach(
node: N | BinaryTreeNodeKey | null,
lesserOrGreaterTraverse(
callback: MapCallback<N> = this._defaultCallbackByKey,
lesserOrGreater: CP = CP.lt,
callback: (node: N) => void
): boolean {
if (typeof node === 'number') node = this.get(node, 'key');
if (!node) return false;
node: N | BinaryTreeNodeKey | null
): MapCallbackReturn<N> {
if (typeof node === 'number') node = this.get(node);
const ans: MapCallbackReturn<N>[] = [];
if (!node) return [];
const key = node.key;

@@ -320,3 +334,3 @@ if (!this.root) return false;

const compared = this._compare(cur.key, key);
if (compared === lesserOrGreater) callback(cur);
if (compared === lesserOrGreater) ans.push(callback(cur));

@@ -336,3 +350,3 @@ if (!cur.left && !cur.right) return;

const compared = this._compare(cur.key, key);
if (compared === lesserOrGreater) callback(cur);
if (compared === lesserOrGreater) ans.push(callback(cur));

@@ -343,3 +357,3 @@ if (cur.left && this._compare(cur.left.key, key) === lesserOrGreater) queue.push(cur.left);

}
return true;
return ans;
}

@@ -364,3 +378,3 @@ }

perfectlyBalance(): boolean {
const sorted = this.dfs('in', 'node'),
const sorted = this.dfs(node => node, 'in'),
n = sorted.length;

@@ -367,0 +381,0 @@ this.clear();

@@ -9,6 +9,5 @@ /**

import type {BinaryTreeNodeKey, TreeMultisetNodeNested, TreeMultisetOptions} from '../../types';
import {BinaryTreeDeletedResult, CP, DFSOrderPattern, FamilyPosition, LoopType} from '../../types';
import {BinaryTreeDeletedResult, CP, FamilyPosition, LoopType} from '../../types';
import {IBinaryTree} from '../../interfaces';
import {AVLTree, AVLTreeNode} from './avl-tree';
import {Queue} from '../queue';

@@ -252,3 +251,3 @@ export class TreeMultisetNode<

override perfectlyBalance(): boolean {
const sorted = this.dfs('in', 'node'),
const sorted = this.dfs(node => node, 'in'),
n = sorted.length;

@@ -356,83 +355,2 @@ if (sorted.length < 1) return false;

/**
* The function `getNodesByCount` returns an array of nodes that have a specific count property, either recursively or
* using a queue.
* @param {BinaryTreeNodeKey | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeKey` or a
* `N`. It represents the property of the nodes that you want to search for.
* @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
* return only one node that matches the `nodeProperty` or all nodes that match the `nodeProperty`. If `onlyOne` is set
* to `true`, the function will return only one node. If `onlyOne`
* @returns an array of nodes that match the given nodeProperty.
*/
getNodesByCount(nodeProperty: BinaryTreeNodeKey | N, onlyOne = false): N[] {
if (!this.root) return [];
const result: N[] = [];
if (this.loopType === LoopType.RECURSIVE) {
const _traverse = (cur: N) => {
if (cur.count === nodeProperty) {
result.push(cur);
if (onlyOne) return;
}
if (!cur.left && !cur.right) return;
cur.left && _traverse(cur.left);
cur.right && _traverse(cur.right);
};
_traverse(this.root);
} else {
const queue = new Queue<N>([this.root]);
while (queue.size > 0) {
const cur = queue.shift();
if (cur) {
if (cur.count === nodeProperty) {
result.push(cur);
if (onlyOne) return result;
}
cur.left && queue.push(cur.left);
cur.right && queue.push(cur.right);
}
}
}
return result;
}
/**
* The BFSCount function returns an array of counts from a breadth-first search of nodes.
* @returns The BFSCount() function returns an array of numbers, specifically the count property of each node in the
* bfs traversal.
*/
bfsCount(): number[] {
const nodes = super.bfs('node');
return nodes.map(node => node.count);
}
/**
* The function "listLevelsCount" takes a node and returns an array of arrays, where each inner array contains the
* count property of each node at that level.
* @param {N | null} node - The parameter `node` is of type `N | null`. This means that it can either be an instance of
* the class `N` or `null`.
* @returns a 2D array of numbers. Each inner array represents a level in the binary tree, and each number in the inner
* array represents the count property of a node in that level.
*/
listLevelsCount(node: N | null): number[][] {
const levels = super.listLevels(node, 'node');
return levels.map(level => level.map(node => node.count));
}
/**
* The `morrisCount` function returns an array of counts for each node in a binary tree, based on a specified traversal
* pattern.
* @param {'in' | 'pre' | 'post'} [pattern] - The `pattern` parameter is an optional parameter that specifies the
* traversal pattern for the Morris traversal algorithm. It can have one of three values: 'in', 'pre', or 'post'.
* @returns The function `morrisCount` returns an array of numbers.
*/
morrisCount(pattern: DFSOrderPattern = 'in'): number[] {
const nodes = super.morris(pattern, 'node');
return nodes.map(node => node.count);
}
/**
* The clear() function clears the data and sets the count to 0.

@@ -439,0 +357,0 @@ */

@@ -175,3 +175,3 @@ /**

* Depth-first search (DFS) method, different traversal orders can be selected。
* @param order - Traversal order parameter: 'in' (in-order), 'pre' (pre-order) or 'post' (post-order).
* @param order - Traverse order parameter: 'in' (in-order), 'pre' (pre-order) or 'post' (post-order).
* @returns An array containing elements traversed in the specified order.

@@ -178,0 +178,0 @@ */

@@ -31,2 +31,6 @@ import {BinaryTreeNode} from '../../data-structures/binary-tree';

export type BFSCallback<N> = (node: N, level?: number) => any;
export type BFSCallbackReturn<N> = ReturnType<BFSCallback<N>>;
export type BinaryTreeNodeProperty<N extends BinaryTreeNode<N['val'], N>> =

@@ -33,0 +37,0 @@ | N['val']

@@ -15,1 +15,4 @@ export * from './binary-tree';

export * from './hash';
export type MapCallback<N> = (node: N) => any;
export type MapCallbackReturn<N> = ReturnType<MapCallback<N>>;

@@ -1,2 +0,2 @@

import {AVLTree, CP} from '../../../../src';
import {AVLTree, CP, AVLTreeNode} from '../../../../src';

@@ -6,3 +6,3 @@ describe('AVL Tree Test', () => {

const arr = [11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5];
const tree = new AVLTree();
const tree = new AVLTree<AVLTreeNode<number>>();

@@ -16,3 +16,3 @@ for (const i of arr) tree.add(i, i);

const getNodeById = tree.get(10, 'key');
const getNodeById = tree.get(10);
expect(getNodeById?.key).toBe(10);

@@ -28,7 +28,7 @@

let subTreeSum = 0;
node15 && tree.subTreeForeach(node15, node => (subTreeSum += node.key));
node15 && tree.subTreeTraverse(node => (subTreeSum += node.key), node15);
expect(subTreeSum).toBe(70);
let lesserSum = 0;
tree.lesserOrGreaterForeach(10, CP.lt, node => (lesserSum += node.key));
tree.lesserOrGreaterTraverse(node => (lesserSum += node.key), CP.lt, 10);
expect(lesserSum).toBe(45);

@@ -39,3 +39,3 @@

const dfs = tree.dfs('in', 'node');
const dfs = tree.dfs(node => node, 'in');
expect(dfs[0].key).toBe(1);

@@ -45,3 +45,4 @@ expect(dfs[dfs.length - 1].key).toBe(16);

tree.perfectlyBalance();
const bfs = tree.bfs('node');
const bfs: AVLTreeNode<number>[] = [];
tree.bfs(node => bfs.push(node));
expect(tree.isPerfectlyBalanced()).toBe(true);

@@ -105,3 +106,4 @@ expect(bfs[0].key).toBe(8);

expect(tree.isAVLBalanced()).toBe(true);
const lastBFSIds = tree.bfs();
const lastBFSIds = new Array<number>();
tree.bfs(node => lastBFSIds.push(node.key));
expect(lastBFSIds[0]).toBe(12);

@@ -111,3 +113,4 @@ expect(lastBFSIds[1]).toBe(2);

const lastBFSNodes = tree.bfs('node');
const lastBFSNodes: AVLTreeNode<number>[] = [];
tree.bfs(node => lastBFSNodes.push(node));
expect(lastBFSNodes[0].key).toBe(12);

@@ -114,0 +117,0 @@ expect(lastBFSNodes[1].key).toBe(2);

@@ -130,3 +130,3 @@ import {BinaryTree, BinaryTreeNode} from '../../../../src';

const inOrder = binaryTree.dfs('in');
const inOrder = binaryTree.dfs(node => node.key);

@@ -133,0 +133,0 @@ expect(inOrder).toEqual([1, 2, 3, 4, 5, 6, 7]);

import {BST, BSTNode, CP} from '../../../../src';
const isDebug = false;
const isDebug = true;

@@ -28,3 +28,3 @@ describe('BST operations test', () => {

const nodeVal9 = bst.get(9, 'val');
const nodeVal9 = bst.get(9, node => node.val);
expect(nodeVal9?.key).toBe(9);

@@ -40,7 +40,7 @@

let subTreeSum = 0;
node15 && bst.subTreeForeach(15, node => (subTreeSum += node.key));
node15 && bst.subTreeTraverse(node => (subTreeSum += node.key), 15);
expect(subTreeSum).toBe(70);
let lesserSum = 0;
bst.lesserOrGreaterForeach(10, CP.lt, node => (lesserSum += node.key));
bst.lesserOrGreaterTraverse(node => (lesserSum += node.key), CP.lt, 10);
expect(lesserSum).toBe(45);

@@ -53,3 +53,3 @@

const dfsInorderNodes = bst.dfs('in', 'node');
const dfsInorderNodes = bst.dfs(node => node, 'in');
expect(dfsInorderNodes[0].key).toBe(1);

@@ -61,3 +61,4 @@ expect(dfsInorderNodes[dfsInorderNodes.length - 1].key).toBe(16);

const bfsNodesAfterBalanced = bst.bfs('node');
const bfsNodesAfterBalanced: BSTNode<number>[] = [];
bst.bfs(node => bfsNodesAfterBalanced.push(node));
expect(bfsNodesAfterBalanced[0].key).toBe(8);

@@ -180,3 +181,4 @@ expect(bfsNodesAfterBalanced[bfsNodesAfterBalanced.length - 1].key).toBe(16);

const bfsIDs = bst.bfs();
const bfsIDs: number[] = [];
bst.bfs(node => bfsIDs.push(node.key));
expect(bfsIDs[0]).toBe(2);

@@ -186,3 +188,4 @@ expect(bfsIDs[1]).toBe(12);

const bfsNodes = bst.bfs('node');
const bfsNodes: BSTNode<number>[] = [];
bst.bfs(node => bfsNodes.push(node));
expect(bfsNodes[0].key).toBe(2);

@@ -231,6 +234,6 @@ expect(bfsNodes[1].key).toBe(12);

const nodeId10 = objBST.get(10, 'key');
const nodeId10 = objBST.get(10);
expect(nodeId10?.key).toBe(10);
const nodeVal9 = objBST.get(9, 'key');
const nodeVal9 = objBST.get(9);
expect(nodeVal9?.key).toBe(9);

@@ -247,7 +250,7 @@

let subTreeSum = 0;
node15 && objBST.subTreeForeach(node15, node => (subTreeSum += node.key));
node15 && objBST.subTreeTraverse(node => (subTreeSum += node.key), node15);
expect(subTreeSum).toBe(70);
let lesserSum = 0;
objBST.lesserOrGreaterForeach(10, CP.lt, node => (lesserSum += node.key));
objBST.lesserOrGreaterTraverse(node => (lesserSum += node.key), CP.lt, 10);
expect(lesserSum).toBe(45);

@@ -260,3 +263,3 @@

const dfsInorderNodes = objBST.dfs('in', 'node');
const dfsInorderNodes = objBST.dfs(node => node, 'in');
expect(dfsInorderNodes[0].key).toBe(1);

@@ -268,3 +271,4 @@ expect(dfsInorderNodes[dfsInorderNodes.length - 1].key).toBe(16);

const bfsNodesAfterBalanced = objBST.bfs('node');
const bfsNodesAfterBalanced: BSTNode<{key: number; keyA: number}>[] = [];
objBST.bfs(node => bfsNodesAfterBalanced.push(node));
expect(bfsNodesAfterBalanced[0].key).toBe(8);

@@ -387,3 +391,4 @@ expect(bfsNodesAfterBalanced[bfsNodesAfterBalanced.length - 1].key).toBe(16);

const bfsIDs = objBST.bfs();
const bfsIDs: number[] = [];
objBST.bfs(node => bfsIDs.push(node.key));
expect(bfsIDs[0]).toBe(2);

@@ -393,3 +398,4 @@ expect(bfsIDs[1]).toBe(12);

const bfsNodes = objBST.bfs('node');
const bfsNodes: BSTNode<{key: number; keyA: number}>[] = [];
objBST.bfs(node => bfsNodes.push(node));
expect(bfsNodes[0].key).toBe(2);

@@ -411,7 +417,7 @@ expect(bfsNodes[1].key).toBe(12);

const startDFS = performance.now();
const dfs = bst.dfs();
const dfs = bst.dfs(node => node);
isDebug && console.log('---bfs', performance.now() - startDFS, dfs.length);
});
it('Should the time consumption of lesserOrGreaterForeach fitting O(n log n)', function () {
it('Should the time consumption of lesserOrGreaterTraverse fitting O(n log n)', function () {
const nodes: number[] = [];

@@ -425,7 +431,31 @@ for (let i = 0; i < inputSize; i++) {

const startL = performance.now();
bst.lesserOrGreaterForeach(inputSize / 2, CP.lt, node => {
return node.key - 1;
});
isDebug && console.log('---lesserOrGreaterForeach', performance.now() - startL);
bst.lesserOrGreaterTraverse(
node => {
node.key - 1;
},
CP.lt,
inputSize / 2
);
isDebug && console.log('---lesserOrGreaterTraverse', performance.now() - startL);
});
it('Should the time consumption of listLevels fitting well', function () {
const nodes: number[] = [];
for (let i = 0; i < inputSize; i++) {
nodes.push(i);
}
const start = performance.now();
bst.addMany(nodes);
isDebug && console.log('---add', performance.now() - start);
const startL = performance.now();
const arr: number[][] = [];
bst.bfs((node, level) => {
if (level !== undefined) {
if (!arr[level]) arr[level] = [];
arr[level].push(node.key);
}
}, true);
isDebug && console.log('---listLevels', arr);
isDebug && console.log('---listLevels', performance.now() - startL);
});
});

@@ -27,3 +27,4 @@ import {AVLTree, BST, BSTNode} from '../../../../src';

expect(bst.isAVLBalanced()).toBe(true);
const bfsIDs = bst.bfs();
const bfsIDs: number[] = [];
bst.bfs(node => bfsIDs.push(node.key));
bfsIDs[0] === 11; // true

@@ -30,0 +31,0 @@ expect(bfsIDs[0]).toBe(11);

@@ -10,3 +10,3 @@ // import {RBTree, RBTreeNode} from '../../../../src';

test('Insertion and In-order Traversal', () => {
test('Insertion and In-order Traverse', () => {
// tree.add(5);

@@ -20,5 +20,5 @@ // tree.add(3);

//
// const inOrderTraversal: number[] = tree.DFS('in')
// const inOrderTraverse: number[] = tree.DFS('in')
//
// expect(inOrderTraversal).toEqual([2, 3, 4, 5, 6, 7, 8]);
// expect(inOrderTraverse).toEqual([2, 3, 4, 5, 6, 7, 8]);
});

@@ -40,7 +40,7 @@

// // Perform in-order traversal to check if the tree is still balanced
// const inOrderTraversal: number[] = tree.DFS('in');
// const inOrderTraverse: number[] = tree.DFS('in');
//
//
// expect(inOrderTraversal).toEqual([2, 4, 5, 6, 7, 8]);
// expect(inOrderTraverse).toEqual([2, 4, 5, 6, 7, 8]);
});
});

@@ -19,3 +19,2 @@ import {CP, TreeMultiset, TreeMultisetNode} from '../../../../src';

expect(treeMultiset.count).toBe(18);
expect(treeMultiset.bfs('key'));

@@ -29,9 +28,9 @@ expect(treeMultiset.has(6));

const nodeVal9 = treeMultiset.get(9, 'val');
const nodeVal9 = treeMultiset.get(9, node => node.val);
expect(nodeVal9?.key).toBe(9);
const nodesByCount1 = treeMultiset.getNodesByCount(1);
const nodesByCount1 = treeMultiset.getNodes(1, node => node.count);
expect(nodesByCount1.length).toBe(14);
const nodesByCount2 = treeMultiset.getNodesByCount(2);
const nodesByCount2 = treeMultiset.getNodes(2, node => node.count);
expect(nodesByCount2.length).toBe(2);

@@ -46,6 +45,6 @@ const leftMost = treeMultiset.getLeftMost();

let subTreeSum = 0;
node15 && treeMultiset.subTreeForeach(15, (node: TreeMultisetNode<number>) => (subTreeSum += node.key));
node15 && treeMultiset.subTreeTraverse((node: TreeMultisetNode<number>) => (subTreeSum += node.key), 15);
expect(subTreeSum).toBe(70);
let lesserSum = 0;
treeMultiset.lesserOrGreaterForeach(10, CP.lt, (node: TreeMultisetNode<number>) => (lesserSum += node.key));
treeMultiset.lesserOrGreaterTraverse((node: TreeMultisetNode<number>) => (lesserSum += node.key), CP.lt, 10);
expect(lesserSum).toBe(45);

@@ -55,3 +54,3 @@

if (node15 instanceof TreeMultisetNode) {
const subTreeAdd = treeMultiset.subTreeForeach(15, (node: TreeMultisetNode<number>) => (node.count += 1));
const subTreeAdd = treeMultiset.subTreeTraverse((node: TreeMultisetNode<number>) => (node.count += 1), 15);
expect(subTreeAdd);

@@ -62,11 +61,7 @@ }

if (node11 instanceof TreeMultisetNode) {
const allGreaterNodesAdded = treeMultiset.lesserOrGreaterForeach(
11,
CP.gt,
(node: TreeMultisetNode<number>) => (node.count += 2)
);
const allGreaterNodesAdded = treeMultiset.lesserOrGreaterTraverse(node => (node.count += 2), CP.gt, 11);
expect(allGreaterNodesAdded);
}
const dfsInorderNodes = treeMultiset.dfs('in', 'node');
const dfsInorderNodes = treeMultiset.dfs(node => node, 'in');
expect(dfsInorderNodes[0].key).toBe(1);

@@ -81,3 +76,3 @@ expect(dfsInorderNodes[dfsInorderNodes.length - 1].key).toBe(16);

const bfsNodesAfterBalanced = treeMultiset.bfs('node');
const bfsNodesAfterBalanced = treeMultiset.bfs(node => node);
expect(bfsNodesAfterBalanced[0].key).toBe(8);

@@ -203,3 +198,3 @@ expect(bfsNodesAfterBalanced[bfsNodesAfterBalanced.length - 1].key).toBe(16);

const bfsIDs = treeMultiset.bfs();
const bfsIDs = treeMultiset.bfs(node => node.key);

@@ -210,3 +205,3 @@ expect(bfsIDs[0]).toBe(12);

const bfsNodes = treeMultiset.bfs('node');
const bfsNodes = treeMultiset.bfs(node => node);

@@ -295,3 +290,3 @@ expect(bfsNodes[0].key).toBe(12);

//
// const dfsInorderNodes = objTreeMultiset.dfs('in', 'node');
// const dfsInorderNodes = objTreeMultiset.dfs(node => node, 'in');
// expect(dfsInorderNodes[0].key).toBe(1);

@@ -486,7 +481,7 @@ // expect(dfsInorderNodes[dfsInorderNodes.length - 1].key).toBe(16);

const startDFS = performance.now();
const dfs = treeMS.dfs();
const dfs = treeMS.dfs(node => node);
isDebug && console.log('---bfs', performance.now() - startDFS, dfs.length);
});
it('Should the time consumption of lesserOrGreaterForeach fitting O(n log n)', function () {
it('Should the time consumption of lesserOrGreaterTraverse fitting O(n log n)', function () {
const start = performance.now();

@@ -498,5 +493,5 @@ for (let i = 0; i < inputSize; i++) {

const startL = performance.now();
treeMS.lesserOrGreaterForeach(inputSize / 2, CP.lt, (node: TreeMultisetNode<number>) => (node.count += 1));
isDebug && console.log('---lesserOrGreaterForeach', performance.now() - startL);
treeMS.lesserOrGreaterTraverse((node: TreeMultisetNode<number>) => (node.count += 1), CP.lt, inputSize / 2);
isDebug && console.log('---lesserOrGreaterTraverse', performance.now() - startL);
});
});

@@ -93,3 +93,3 @@ import {MaxPriorityQueue} from '../../../../src';

const cost = performance.now() - startTime;
expect(cost).toBeLessThan(bigO.LINEAR * 20);
expect(cost).toBeLessThan(bigO.LINEAR * 30);
expect(prev).toBeGreaterThan(0);

@@ -96,0 +96,0 @@ });

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc