bst-typed 1.19.3 → 1.19.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,180 +1,30 @@
1
1
  # What
2
-
3
2
  ## Brief
4
- Javascript & TypeScript Data Structure Library.
5
-
6
- Binary Tree, Binary Search Tree (BST), AVL Tree, Tree Multiset, Segment Tree, Binary Indexed Tree, Graph, Directed Graph, Undirected Graph, Linked List, Singly Linked List, Doubly Linked List, Queue, Object Deque, Array Deque, Stack, Hash, Coordinate Set, Coordinate Map, Heap, Priority Queue, Max Priority Queue, Min Priority Queue, Trie
7
-
8
- ## Algorithms list only a few out, you can discover more in API docs
3
+ This is a standalone BST (Binary Search Tree) data structure from the data-structure-typed collection. If you wish to access more data structures or advanced features, you can transition to directly installing the complete [data-structure-typed](https://www.npmjs.com/package/data-structure-typed) package
9
4
 
10
- DFS, DFSIterative, BFS, morris, Bellman-Ford Algorithm, Dijkstra's Algorithm, Floyd-Warshall Algorithm, Tarjan's Algorithm
11
-
12
- ## Code design
13
- By strictly adhering to object-oriented design (BinaryTree -> BST -> AVLTree -> TreeMultiset), you can seamlessly inherit the existing data structures to implement the customized ones you need. Object-oriented design stands as the optimal approach to data structure design.
14
5
 
15
6
  # How
16
7
 
17
8
  ## install
18
- ### yarn
19
-
9
+ ### npm
20
10
  ```bash
21
- yarn add data-structure-typed
11
+ npm i bst-typed
22
12
  ```
23
-
24
- ### npm
25
-
13
+ ### yarn
26
14
  ```bash
27
- npm install data-structure-typed
15
+ yarn add bst-typed
28
16
  ```
29
17
 
30
- ### Binary Search Tree (BST) snippet
31
-
18
+ ### snippet
32
19
  #### TS
33
20
  ```typescript
34
- import {BST, BSTNode} from 'data-structure-typed';
35
-
36
- const bst = new BST();
37
- bst.add(11);
38
- bst.add(3);
39
- bst.addMany([15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);
40
- bst.size === 16; // true
41
- bst.has(6); // true
42
- const node6 = bst.get(6);
43
- bst.getHeight(6) === 2; // true
44
- bst.getHeight() === 5; // true
45
- bst.getDepth(6) === 3; // true
46
- const leftMost = bst.getLeftMost();
47
- leftMost?.id === 1; // true
48
- expect(leftMost?.id).toBe(1);
49
- bst.remove(6);
50
- bst.get(6); // null
51
- bst.isAVLBalanced(); // true or false
52
- const bfsIDs = bst.BFS();
53
- bfsIDs[0] === 11; // true
54
- expect(bfsIDs[0]).toBe(11);
55
-
56
- const objBST = new BST<BSTNode<{ id: number, keyA: number }>>();
57
- objBST.add(11, {id: 11, keyA: 11});
58
- objBST.add(3, {id: 3, keyA: 3});
59
-
60
- objBST.addMany([{id: 15, keyA: 15}, {id: 1, keyA: 1}, {id: 8, keyA: 8},
61
- {id: 13, keyA: 13}, {id: 16, keyA: 16}, {id: 2, keyA: 2},
62
- {id: 6, keyA: 6}, {id: 9, keyA: 9}, {id: 12, keyA: 12},
63
- {id: 14, keyA: 14}, {id: 4, keyA: 4}, {id: 7, keyA: 7},
64
- {id: 10, keyA: 10}, {id: 5, keyA: 5}]);
65
-
66
- objBST.remove(11);
67
-
68
-
69
- const avlTree = new AVLTree();
70
- avlTree.addMany([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5])
71
- avlTree.isAVLBalanced(); // true
72
- avlTree.remove(10);
73
- avlTree.isAVLBalanced(); // true
74
21
 
75
22
  ```
76
23
  #### JS
77
24
  ```javascript
78
- const {BST, BSTNode} = require('data-structure-typed');
79
-
80
- const bst = new BST();
81
- bst.add(11);
82
- bst.add(3);
83
- bst.addMany([15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);
84
- bst.size === 16; // true
85
- bst.has(6); // true
86
- const node6 = bst.get(6);
87
- bst.getHeight(6) === 2; // true
88
- bst.getHeight() === 5; // true
89
- bst.getDepth(6) === 3; // true
90
- const leftMost = bst.getLeftMost();
91
- leftMost?.id === 1; // true
92
- expect(leftMost?.id).toBe(1);
93
- bst.remove(6);
94
- bst.get(6); // null
95
- bst.isAVLBalanced(); // true or false
96
- const bfsIDs = bst.BFS();
97
- bfsIDs[0] === 11; // true
98
- expect(bfsIDs[0]).toBe(11);
99
-
100
- const objBST = new BST();
101
- objBST.add(11, {id: 11, keyA: 11});
102
- objBST.add(3, {id: 3, keyA: 3});
103
-
104
- objBST.addMany([{id: 15, keyA: 15}, {id: 1, keyA: 1}, {id: 8, keyA: 8},
105
- {id: 13, keyA: 13}, {id: 16, keyA: 16}, {id: 2, keyA: 2},
106
- {id: 6, keyA: 6}, {id: 9, keyA: 9}, {id: 12, keyA: 12},
107
- {id: 14, keyA: 14}, {id: 4, keyA: 4}, {id: 7, keyA: 7},
108
- {id: 10, keyA: 10}, {id: 5, keyA: 5}]);
109
-
110
- objBST.remove(11);
111
-
112
-
113
- const avlTree = new AVLTree();
114
- avlTree.addMany([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5])
115
- avlTree.isAVLBalanced(); // true
116
- avlTree.remove(10);
117
- avlTree.isAVLBalanced(); // true
118
-
119
- ```
120
-
121
- ### Directed Graph simple snippet
122
25
 
123
- #### TS or JS
124
- ```typescript
125
- import {DirectedGraph} from 'data-structure-typed';
126
-
127
- const graph = new DirectedGraph();
128
-
129
- graph.addVertex('A');
130
- graph.addVertex('B');
131
-
132
- graph.hasVertex('A'); // true
133
- graph.hasVertex('B'); // true
134
- graph.hasVertex('C'); // false
135
-
136
- graph.addEdge('A', 'B');
137
- graph.hasEdge('A', 'B'); // true
138
- graph.hasEdge('B', 'A'); // false
139
-
140
- graph.removeEdgeSrcToDest('A', 'B');
141
- graph.hasEdge('A', 'B'); // false
142
-
143
- graph.addVertex('C');
144
-
145
- graph.addEdge('A', 'B');
146
- graph.addEdge('B', 'C');
147
-
148
- const topologicalOrderIds = graph.topologicalSort(); // ['A', 'B', 'C']
149
- ```
150
-
151
- ### Undirected Graph snippet
152
-
153
- #### TS or JS
154
- ```typescript
155
- import {UndirectedGraph} from 'data-structure-typed';
156
-
157
- const graph = new UndirectedGraph();
158
- graph.addVertex('A');
159
- graph.addVertex('B');
160
- graph.addVertex('C');
161
- graph.addVertex('D');
162
- graph.removeVertex('C');
163
- graph.addEdge('A', 'B');
164
- graph.addEdge('B', 'D');
165
-
166
- const dijkstraResult = graph.dijkstra('A');
167
- Array.from(dijkstraResult?.seen ?? []).map(vertex => vertex.id) // ['A', 'B', 'D']
168
26
  ```
169
27
 
170
- ![](https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/examples/dfs-pre-order.webp)
171
-
172
- ![](https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/examples/test-graphs.webp)
173
-
174
- ![](https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/examples/cut-off-trees-for-golf.webp)
175
-
176
- ![](https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/examples/parenthesis-check.webp)
177
-
178
28
 
179
29
  ## API docs & Examples
180
30
 
@@ -182,10 +32,6 @@ import {UndirectedGraph} from 'data-structure-typed';
182
32
 
183
33
  [Live Examples](https://data-structure-typed-examples.vercel.app)
184
34
 
185
- <a href="https://data-structure-typed-examples.vercel.app" target="_blank">Live Examples</a>
186
-
187
- [//]: # ([Examples Repository]&#40;https://github.com/zrwusa/data-structure-typed-examples&#41;)
188
-
189
35
  <a href="https://github.com/zrwusa/data-structure-typed-examples" target="_blank">Examples Repository</a>
190
36
 
191
37
  ## Data Structures
@@ -203,10 +49,10 @@ import {UndirectedGraph} from 'data-structure-typed';
203
49
  <tbody>
204
50
  <tr>
205
51
  <td>Binary Tree</td>
206
- <td><img src="https://raw.githubusercontent.com/zrwusa/assets/master/images/data-structure-typed/assets/tick.svg" alt="">
207
- </img></td>
208
- <td><img src="https://raw.githubusercontent.com/zrwusa/assets/master/images/data-structure-typed/assets/tick.svg" alt="">
209
- </img></td>
52
+ <td><img src="https://raw.githubusercontent.com/zrwusa/assets/master/images/data-structure-typed/assets/tick.svg" alt=""/>
53
+ </td>
54
+ <td><img src="https://raw.githubusercontent.com/zrwusa/assets/master/images/data-structure-typed/assets/tick.svg" alt=""/>
55
+ </td>
210
56
  <td><a href="https://data-structure-typed-docs.vercel.app/classes/BinaryTree.html"><span>Binary Tree</span></a></td>
211
57
  <td><img src="https://raw.githubusercontent.com/zrwusa/assets/master/images/data-structure-typed/assets/tick.svg" alt=""></td>
212
58
  </tr>
@@ -653,46 +499,6 @@ import {UndirectedGraph} from 'data-structure-typed';
653
499
 
654
500
  ![complexities of data structures](https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/assets/data-structure-complexities.jpg)
655
501
 
656
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/binary-tree/bst-rotation.gif&#41;)
657
-
658
- [//]: # ()
659
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/binary-tree/avl-tree-inserting.gif&#41;)
660
-
661
- [//]: # ()
662
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/tarjan.webp&#41;)
663
-
664
- [//]: # ()
665
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/adjacency-list.jpg&#41;)
666
-
667
- [//]: # ()
668
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/adjacency-list-pros-cons.jpg&#41;)
669
-
670
- [//]: # ()
671
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/adjacency-matrix.jpg&#41;)
672
-
673
- [//]: # ()
674
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/adjacency-matrix-pros-cons.jpg&#41;)
675
-
676
- [//]: # ()
677
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/dfs-can-do.jpg&#41;)
678
-
679
- [//]: # ()
680
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/edge-list.jpg&#41;)
681
-
682
- [//]: # ()
683
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/edge-list-pros-cons.jpg&#41;)
684
-
685
- [//]: # ()
686
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/max-flow.jpg&#41;)
687
-
688
- [//]: # ()
689
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/mst.jpg&#41;)
690
-
691
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/tarjan-articulation-point-bridge.png&#41;)
692
-
693
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/tarjan-complicate-simple.png&#41;)
694
-
695
- [//]: # (![]&#40;https://github.com/zrwusa/assets/blob/master/images/data-structure-typed/graph/tarjan-strongly-connected-component.png&#41;)
696
502
 
697
503
 
698
504
 
package/dist/index.d.ts CHANGED
@@ -1 +1,8 @@
1
- export * from './bst';
1
+ /**
2
+ * data-structure-typed
3
+ *
4
+ * @author Tyler Zeng
5
+ * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
6
+ * @license MIT License
7
+ */
8
+ export { BSTNode, BST } from 'data-structure-typed';
package/dist/index.js CHANGED
@@ -1,17 +1,13 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
2
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./bst"), exports);
3
+ exports.BST = exports.BSTNode = void 0;
4
+ /**
5
+ * data-structure-typed
6
+ *
7
+ * @author Tyler Zeng
8
+ * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
9
+ * @license MIT License
10
+ */
11
+ var data_structure_typed_1 = require("data-structure-typed");
12
+ Object.defineProperty(exports, "BSTNode", { enumerable: true, get: function () { return data_structure_typed_1.BSTNode; } });
13
+ Object.defineProperty(exports, "BST", { enumerable: true, get: function () { return data_structure_typed_1.BST; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bst-typed",
3
- "version": "1.19.3",
3
+ "version": "1.19.5",
4
4
  "description": "BST (Binary Search Tree). Javascript & Typescript Data Structure.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -65,7 +65,7 @@
65
65
  "typescript": "^4.9.5"
66
66
  },
67
67
  "dependencies": {
68
- "data-structure-typed": "^1.19.3",
68
+ "data-structure-typed": "^1.19.5",
69
69
  "zod": "^3.22.2"
70
70
  }
71
71
  }
package/tsconfig.json CHANGED
@@ -3,9 +3,10 @@
3
3
  "declaration": true,
4
4
  "outDir": "./dist",
5
5
  "module": "commonjs",
6
- "target": "es5",
6
+ "target": "es6",
7
7
  "lib": [
8
- "esnext",
8
+ // "es2015",
9
+ "esnext"
9
10
  ],
10
11
  "strict": true,
11
12
  "esModuleInterop": true,
@@ -30,8 +31,9 @@
30
31
  "src",
31
32
  ],
32
33
  "exclude": [
33
- // "node_modules/data-structure-typed",
34
+ // "node_modules/data-structure-typed",
34
35
  "node_modules",
35
36
  "dist"
36
37
  ]
37
- }
38
+ }
39
+
package/dist/bst.d.ts DELETED
@@ -1,119 +0,0 @@
1
- /**
2
- * data-structure-typed
3
- *
4
- * @author Tyler Zeng
5
- * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
6
- * @license MIT License
7
- */
8
- import type { BinaryTreeNodeId, BinaryTreeNodePropertyName, BSTComparator, BSTNodeNested, BSTOptions } from 'data-structure-typed';
9
- import { BinaryTree, BinaryTreeNode, CP, IBST, IBSTNode } from 'data-structure-typed';
10
- export declare class BSTNode<T = any, NEIGHBOR extends BSTNode<T, NEIGHBOR> = BSTNodeNested<T>> extends BinaryTreeNode<T, NEIGHBOR> implements IBSTNode<T, NEIGHBOR> {
11
- }
12
- export declare class BST<N extends BSTNode<N['val'], N> = BSTNode> extends BinaryTree<N> implements IBST<N> {
13
- /**
14
- * The constructor function initializes a binary search tree object with an optional comparator function.
15
- * @param {BSTOptions} [options] - An optional object that contains configuration options for the binary search tree.
16
- */
17
- constructor(options?: BSTOptions);
18
- /**
19
- * The function creates a new binary search tree node with the given id and value.
20
- * @param {BinaryTreeNodeId} id - The `id` parameter is the identifier for the binary tree node. It is used to uniquely
21
- * identify each node in the binary tree.
22
- * @param [val] - The `val` parameter is an optional value that can be assigned to the node. It represents the value
23
- * that will be stored in the node.
24
- * @returns a new instance of the BSTNode class with the specified id and value.
25
- */
26
- createNode(id: BinaryTreeNodeId, val?: N['val']): N;
27
- /**
28
- * The `add` function adds a new node to a binary tree, ensuring that duplicates are not accepted.
29
- * @param {BinaryTreeNodeId} id - The `id` parameter is the identifier of the binary tree node that we want to add. It
30
- * is of type `BinaryTreeNodeId`.
31
- * @param [val] - The `val` parameter is an optional value that can be assigned to the node being added. It represents
32
- * the value associated with the node.
33
- * @returns The function `add` returns the inserted node (`inserted`) if it was successfully added to the binary tree.
34
- * If the node was not added (e.g., due to a duplicate ID), it returns `null` or `undefined`.
35
- */
36
- add(id: BinaryTreeNodeId, val?: N['val']): N | null | undefined;
37
- /**
38
- * The function returns the first node in a binary tree that matches the given property name and value.
39
- * @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
40
- * generic type `N`. It represents the property of the binary tree node that you want to search for.
41
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
42
- * specifies the property name to use for searching the binary tree nodes. If not provided, it defaults to `'id'`.
43
- * @returns The method is returning either a BinaryTreeNodeId or N (generic type) or null.
44
- */
45
- get(nodeProperty: BinaryTreeNodeId | N, propertyName?: BinaryTreeNodePropertyName): N | null;
46
- /**
47
- * The function returns the id of the rightmost node if the comparison between two values is less than, the id of the
48
- * leftmost node if the comparison is greater than, and the id of the rightmost node otherwise.
49
- * @returns The method `lastKey()` returns the id of the rightmost node in the binary tree if the comparison between
50
- * the values at index 0 and 1 is less than, otherwise it returns the id of the leftmost node. If the comparison is
51
- * equal, it returns the id of the rightmost node. If there are no nodes in the tree, it returns 0.
52
- */
53
- lastKey(): BinaryTreeNodeId;
54
- /**
55
- * The function `getNodes` returns an array of nodes in a binary tree that match a given property value.
56
- * @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or an
57
- * `N` type. It represents the property of the binary tree node that you want to compare with.
58
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
59
- * specifies the property name to use for comparison. If not provided, it defaults to `'id'`.
60
- * @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
61
- * return only one node that matches the given `nodeProperty` or all nodes that match the `nodeProperty`. If `onlyOne`
62
- * is set to `true`, the function will return an array with only one node (if
63
- * @returns an array of nodes (type N).
64
- */
65
- getNodes(nodeProperty: BinaryTreeNodeId | N, propertyName?: BinaryTreeNodePropertyName, onlyOne?: boolean): N[];
66
- /**
67
- * The `lesserSum` function calculates the sum of property values in a binary tree for nodes that have a property value
68
- * less than a given node.
69
- * @param {N | BinaryTreeNodeId | null} beginNode - The `beginNode` parameter can be one of the following:
70
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
71
- * specifies the property name to use for calculating the sum. If not provided, it defaults to `'id'`.
72
- * @returns The function `lesserSum` returns a number, which represents the sum of the values of the nodes in the
73
- * binary tree that have a lesser value than the specified `beginNode` based on the `propertyName`.
74
- */
75
- lesserSum(beginNode: N | BinaryTreeNodeId | null, propertyName?: BinaryTreeNodePropertyName): number;
76
- /**
77
- * The `allGreaterNodesAdd` function adds a delta value to the specified property of all nodes in a binary tree that
78
- * have a greater value than a given node.
79
- * @param {N | BinaryTreeNodeId | null} node - The `node` parameter can be either of type `N` (a generic type),
80
- * `BinaryTreeNodeId`, or `null`. It represents the node in the binary tree to which the delta value will be added.
81
- * @param {number} delta - The `delta` parameter is a number that represents the amount by which the property value of
82
- * each greater node should be increased.
83
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
84
- * specifies the property name of the nodes in the binary tree that you want to update. If not provided, it defaults to
85
- * 'id'.
86
- * @returns a boolean value.
87
- */
88
- allGreaterNodesAdd(node: N | BinaryTreeNodeId | null, delta: number, propertyName?: BinaryTreeNodePropertyName): boolean;
89
- /**
90
- * Balancing Adjustment:
91
- * Perfectly Balanced Binary Tree: Since the balance of a perfectly balanced binary tree is already fixed, no additional balancing adjustment is needed. Any insertion or deletion operation will disrupt the perfect balance, often requiring a complete reconstruction of the tree.
92
- * AVL Tree: After insertion or deletion operations, an AVL tree performs rotation adjustments based on the balance factor of nodes to restore the tree's balance. These rotations can be left rotations, right rotations, left-right rotations, or right-left rotations, performed as needed.
93
- *
94
- * Use Cases and Efficiency:
95
- * Perfectly Balanced Binary Tree: Perfectly balanced binary trees are typically used in specific scenarios such as complete binary heaps in heap sort or certain types of Huffman trees. However, they are not suitable for dynamic operations requiring frequent insertions and deletions, as these operations often necessitate full tree reconstruction.
96
- * AVL Tree: AVL trees are well-suited for scenarios involving frequent searching, insertion, and deletion operations. Through rotation adjustments, AVL trees maintain their balance, ensuring average and worst-case time complexity of O(log n).
97
- */
98
- /**
99
- * The `perfectlyBalance` function takes a binary tree, performs a depth-first search to sort the nodes, and then
100
- * constructs a balanced binary search tree using either a recursive or iterative approach.
101
- * @returns The function `perfectlyBalance()` returns a boolean value.
102
- */
103
- perfectlyBalance(): boolean;
104
- /**
105
- * The function `isAVLBalanced` checks if a binary tree is balanced according to the AVL tree property.
106
- * @returns a boolean value.
107
- */
108
- isAVLBalanced(): boolean;
109
- protected _comparator: BSTComparator;
110
- /**
111
- * The function compares two binary tree node IDs using a comparator function and returns whether the first ID is
112
- * greater than, less than, or equal to the second ID.
113
- * @param {BinaryTreeNodeId} a - a is a BinaryTreeNodeId, which represents the identifier of a binary tree node.
114
- * @param {BinaryTreeNodeId} b - The parameter "b" in the above code refers to a BinaryTreeNodeId.
115
- * @returns a value of type CP (ComparisonResult). The possible return values are CP.gt (greater than), CP.lt (less
116
- * than), or CP.eq (equal).
117
- */
118
- protected _compare(a: BinaryTreeNodeId, b: BinaryTreeNodeId): CP;
119
- }
package/dist/bst.js DELETED
@@ -1,507 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __read = (this && this.__read) || function (o, n) {
18
- var m = typeof Symbol === "function" && o[Symbol.iterator];
19
- if (!m) return o;
20
- var i = m.call(o), r, ar = [], e;
21
- try {
22
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
23
- }
24
- catch (error) { e = { error: error }; }
25
- finally {
26
- try {
27
- if (r && !r.done && (m = i["return"])) m.call(i);
28
- }
29
- finally { if (e) throw e.error; }
30
- }
31
- return ar;
32
- };
33
- Object.defineProperty(exports, "__esModule", { value: true });
34
- exports.BST = exports.BSTNode = void 0;
35
- var data_structure_typed_1 = require("data-structure-typed");
36
- var BSTNode = /** @class */ (function (_super) {
37
- __extends(BSTNode, _super);
38
- function BSTNode() {
39
- return _super !== null && _super.apply(this, arguments) || this;
40
- }
41
- return BSTNode;
42
- }(data_structure_typed_1.BinaryTreeNode));
43
- exports.BSTNode = BSTNode;
44
- var BST = /** @class */ (function (_super) {
45
- __extends(BST, _super);
46
- /**
47
- * The constructor function initializes a binary search tree object with an optional comparator function.
48
- * @param {BSTOptions} [options] - An optional object that contains configuration options for the binary search tree.
49
- */
50
- function BST(options) {
51
- var _this = _super.call(this, options) || this;
52
- _this._comparator = function (a, b) { return a - b; };
53
- if (options !== undefined) {
54
- var comparator = options.comparator;
55
- if (comparator !== undefined) {
56
- _this._comparator = comparator;
57
- }
58
- }
59
- return _this;
60
- }
61
- /**
62
- * The function creates a new binary search tree node with the given id and value.
63
- * @param {BinaryTreeNodeId} id - The `id` parameter is the identifier for the binary tree node. It is used to uniquely
64
- * identify each node in the binary tree.
65
- * @param [val] - The `val` parameter is an optional value that can be assigned to the node. It represents the value
66
- * that will be stored in the node.
67
- * @returns a new instance of the BSTNode class with the specified id and value.
68
- */
69
- BST.prototype.createNode = function (id, val) {
70
- return new BSTNode(id, val);
71
- };
72
- /**
73
- * The `add` function adds a new node to a binary tree, ensuring that duplicates are not accepted.
74
- * @param {BinaryTreeNodeId} id - The `id` parameter is the identifier of the binary tree node that we want to add. It
75
- * is of type `BinaryTreeNodeId`.
76
- * @param [val] - The `val` parameter is an optional value that can be assigned to the node being added. It represents
77
- * the value associated with the node.
78
- * @returns The function `add` returns the inserted node (`inserted`) if it was successfully added to the binary tree.
79
- * If the node was not added (e.g., due to a duplicate ID), it returns `null` or `undefined`.
80
- */
81
- BST.prototype.add = function (id, val) {
82
- var inserted = null;
83
- var newNode = this.createNode(id, val);
84
- if (this.root === null) {
85
- this._setRoot(newNode);
86
- this._setSize(this.size + 1);
87
- inserted = (this.root);
88
- }
89
- else {
90
- var cur = this.root;
91
- var traversing = true;
92
- while (traversing) {
93
- if (cur !== null && newNode !== null) {
94
- if (this._compare(cur.id, id) === data_structure_typed_1.CP.eq) {
95
- if (newNode) {
96
- cur.val = newNode.val;
97
- }
98
- //Duplicates are not accepted.
99
- traversing = false;
100
- inserted = cur;
101
- }
102
- else if (this._compare(cur.id, id) === data_structure_typed_1.CP.gt) {
103
- // Traverse left of the node
104
- if (cur.left === undefined) {
105
- if (newNode) {
106
- newNode.parent = cur;
107
- }
108
- //Add to the left of the current node
109
- cur.left = newNode;
110
- this._setSize(this.size + 1);
111
- traversing = false;
112
- inserted = cur.left;
113
- }
114
- else {
115
- //Traverse the left of the current node
116
- if (cur.left)
117
- cur = cur.left;
118
- }
119
- }
120
- else if (this._compare(cur.id, id) === data_structure_typed_1.CP.lt) {
121
- // Traverse right of the node
122
- if (cur.right === undefined) {
123
- if (newNode) {
124
- newNode.parent = cur;
125
- }
126
- //Add to the right of the current node
127
- cur.right = newNode;
128
- this._setSize(this.size + 1);
129
- traversing = false;
130
- inserted = (cur.right);
131
- }
132
- else {
133
- //Traverse the left of the current node
134
- if (cur.right)
135
- cur = cur.right;
136
- }
137
- }
138
- }
139
- else {
140
- traversing = false;
141
- }
142
- }
143
- }
144
- return inserted;
145
- };
146
- /**
147
- * The function returns the first node in a binary tree that matches the given property name and value.
148
- * @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
149
- * generic type `N`. It represents the property of the binary tree node that you want to search for.
150
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
151
- * specifies the property name to use for searching the binary tree nodes. If not provided, it defaults to `'id'`.
152
- * @returns The method is returning either a BinaryTreeNodeId or N (generic type) or null.
153
- */
154
- BST.prototype.get = function (nodeProperty, propertyName) {
155
- var _a;
156
- propertyName = propertyName !== null && propertyName !== void 0 ? propertyName : 'id';
157
- return (_a = this.getNodes(nodeProperty, propertyName, true)[0]) !== null && _a !== void 0 ? _a : null;
158
- };
159
- /**
160
- * The function returns the id of the rightmost node if the comparison between two values is less than, the id of the
161
- * leftmost node if the comparison is greater than, and the id of the rightmost node otherwise.
162
- * @returns The method `lastKey()` returns the id of the rightmost node in the binary tree if the comparison between
163
- * the values at index 0 and 1 is less than, otherwise it returns the id of the leftmost node. If the comparison is
164
- * equal, it returns the id of the rightmost node. If there are no nodes in the tree, it returns 0.
165
- */
166
- BST.prototype.lastKey = function () {
167
- var _a, _b, _c, _d, _e, _f;
168
- if (this._compare(0, 1) === data_structure_typed_1.CP.lt)
169
- return (_b = (_a = this.getRightMost()) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : 0;
170
- else if (this._compare(0, 1) === data_structure_typed_1.CP.gt)
171
- return (_d = (_c = this.getLeftMost()) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : 0;
172
- else
173
- return (_f = (_e = this.getRightMost()) === null || _e === void 0 ? void 0 : _e.id) !== null && _f !== void 0 ? _f : 0;
174
- };
175
- /**
176
- * The function `getNodes` returns an array of nodes in a binary tree that match a given property value.
177
- * @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or an
178
- * `N` type. It represents the property of the binary tree node that you want to compare with.
179
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
180
- * specifies the property name to use for comparison. If not provided, it defaults to `'id'`.
181
- * @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
182
- * return only one node that matches the given `nodeProperty` or all nodes that match the `nodeProperty`. If `onlyOne`
183
- * is set to `true`, the function will return an array with only one node (if
184
- * @returns an array of nodes (type N).
185
- */
186
- BST.prototype.getNodes = function (nodeProperty, propertyName, onlyOne) {
187
- var _this = this;
188
- propertyName = propertyName !== null && propertyName !== void 0 ? propertyName : 'id';
189
- if (!this.root)
190
- return [];
191
- var result = [];
192
- if (this.loopType === data_structure_typed_1.LoopType.RECURSIVE) {
193
- var _traverse_1 = function (cur) {
194
- if (_this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne))
195
- return;
196
- if (!cur.left && !cur.right)
197
- return;
198
- if (propertyName === 'id') {
199
- if (_this._compare(cur.id, nodeProperty) === data_structure_typed_1.CP.gt)
200
- cur.left && _traverse_1(cur.left);
201
- if (_this._compare(cur.id, nodeProperty) === data_structure_typed_1.CP.lt)
202
- cur.right && _traverse_1(cur.right);
203
- }
204
- else {
205
- cur.left && _traverse_1(cur.left);
206
- cur.right && _traverse_1(cur.right);
207
- }
208
- };
209
- _traverse_1(this.root);
210
- }
211
- else {
212
- var queue = [this.root];
213
- while (queue.length > 0) {
214
- var cur = queue.shift();
215
- if (cur) {
216
- if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne))
217
- return result;
218
- if (propertyName === 'id') {
219
- if (this._compare(cur.id, nodeProperty) === data_structure_typed_1.CP.gt)
220
- cur.left && queue.push(cur.left);
221
- if (this._compare(cur.id, nodeProperty) === data_structure_typed_1.CP.lt)
222
- cur.right && queue.push(cur.right);
223
- }
224
- else {
225
- cur.left && queue.push(cur.left);
226
- cur.right && queue.push(cur.right);
227
- }
228
- }
229
- }
230
- }
231
- return result;
232
- };
233
- // --- start additional functions
234
- /**
235
- * The `lesserSum` function calculates the sum of property values in a binary tree for nodes that have a property value
236
- * less than a given node.
237
- * @param {N | BinaryTreeNodeId | null} beginNode - The `beginNode` parameter can be one of the following:
238
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
239
- * specifies the property name to use for calculating the sum. If not provided, it defaults to `'id'`.
240
- * @returns The function `lesserSum` returns a number, which represents the sum of the values of the nodes in the
241
- * binary tree that have a lesser value than the specified `beginNode` based on the `propertyName`.
242
- */
243
- BST.prototype.lesserSum = function (beginNode, propertyName) {
244
- var _this = this;
245
- propertyName = propertyName !== null && propertyName !== void 0 ? propertyName : 'id';
246
- if (typeof beginNode === 'number')
247
- beginNode = this.get(beginNode, 'id');
248
- if (!beginNode)
249
- return 0;
250
- if (!this.root)
251
- return 0;
252
- var id = beginNode.id;
253
- var getSumByPropertyName = function (cur) {
254
- var needSum;
255
- switch (propertyName) {
256
- case 'id':
257
- needSum = cur.id;
258
- break;
259
- default:
260
- needSum = cur.id;
261
- break;
262
- }
263
- return needSum;
264
- };
265
- var sum = 0;
266
- if (this.loopType === data_structure_typed_1.LoopType.RECURSIVE) {
267
- var _traverse_2 = function (cur) {
268
- var compared = _this._compare(cur.id, id);
269
- if (compared === data_structure_typed_1.CP.eq) {
270
- if (cur.right)
271
- sum += _this.subTreeSum(cur.right, propertyName);
272
- return;
273
- }
274
- else if (compared === data_structure_typed_1.CP.lt) {
275
- if (cur.left)
276
- sum += _this.subTreeSum(cur.left, propertyName);
277
- sum += getSumByPropertyName(cur);
278
- if (cur.right)
279
- _traverse_2(cur.right);
280
- else
281
- return;
282
- }
283
- else {
284
- if (cur.left)
285
- _traverse_2(cur.left);
286
- else
287
- return;
288
- }
289
- };
290
- _traverse_2(this.root);
291
- }
292
- else {
293
- var queue = [this.root];
294
- while (queue.length > 0) {
295
- var cur = queue.shift();
296
- if (cur) {
297
- var compared = this._compare(cur.id, id);
298
- if (compared === data_structure_typed_1.CP.eq) {
299
- if (cur.right)
300
- sum += this.subTreeSum(cur.right, propertyName);
301
- return sum;
302
- }
303
- else if (compared === data_structure_typed_1.CP.lt) { // todo maybe a bug
304
- if (cur.left)
305
- sum += this.subTreeSum(cur.left, propertyName);
306
- sum += getSumByPropertyName(cur);
307
- if (cur.right)
308
- queue.push(cur.right);
309
- else
310
- return sum;
311
- }
312
- else {
313
- if (cur.left)
314
- queue.push(cur.left);
315
- else
316
- return sum;
317
- }
318
- }
319
- }
320
- }
321
- return sum;
322
- };
323
- /**
324
- * The `allGreaterNodesAdd` function adds a delta value to the specified property of all nodes in a binary tree that
325
- * have a greater value than a given node.
326
- * @param {N | BinaryTreeNodeId | null} node - The `node` parameter can be either of type `N` (a generic type),
327
- * `BinaryTreeNodeId`, or `null`. It represents the node in the binary tree to which the delta value will be added.
328
- * @param {number} delta - The `delta` parameter is a number that represents the amount by which the property value of
329
- * each greater node should be increased.
330
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
331
- * specifies the property name of the nodes in the binary tree that you want to update. If not provided, it defaults to
332
- * 'id'.
333
- * @returns a boolean value.
334
- */
335
- BST.prototype.allGreaterNodesAdd = function (node, delta, propertyName) {
336
- var _this = this;
337
- propertyName = propertyName !== null && propertyName !== void 0 ? propertyName : 'id';
338
- if (typeof node === 'number')
339
- node = this.get(node, 'id');
340
- if (!node)
341
- return false;
342
- var id = node.id;
343
- if (!this.root)
344
- return false;
345
- var _sumByPropertyName = function (cur) {
346
- switch (propertyName) {
347
- case 'id':
348
- cur.id += delta;
349
- break;
350
- default:
351
- cur.id += delta;
352
- break;
353
- }
354
- };
355
- if (this.loopType === data_structure_typed_1.LoopType.RECURSIVE) {
356
- var _traverse_3 = function (cur) {
357
- var compared = _this._compare(cur.id, id);
358
- if (compared === data_structure_typed_1.CP.gt)
359
- _sumByPropertyName(cur);
360
- if (!cur.left && !cur.right)
361
- return;
362
- if (cur.left && _this._compare(cur.left.id, id) === data_structure_typed_1.CP.gt)
363
- _traverse_3(cur.left);
364
- if (cur.right && _this._compare(cur.right.id, id) === data_structure_typed_1.CP.gt)
365
- _traverse_3(cur.right);
366
- };
367
- _traverse_3(this.root);
368
- return true;
369
- }
370
- else {
371
- var queue = [this.root];
372
- while (queue.length > 0) {
373
- var cur = queue.shift();
374
- if (cur) {
375
- var compared = this._compare(cur.id, id);
376
- if (compared === data_structure_typed_1.CP.gt)
377
- _sumByPropertyName(cur);
378
- if (cur.left && this._compare(cur.left.id, id) === data_structure_typed_1.CP.gt)
379
- queue.push(cur.left);
380
- if (cur.right && this._compare(cur.right.id, id) === data_structure_typed_1.CP.gt)
381
- queue.push(cur.right);
382
- }
383
- }
384
- return true;
385
- }
386
- };
387
- /**
388
- * Balancing Adjustment:
389
- * Perfectly Balanced Binary Tree: Since the balance of a perfectly balanced binary tree is already fixed, no additional balancing adjustment is needed. Any insertion or deletion operation will disrupt the perfect balance, often requiring a complete reconstruction of the tree.
390
- * AVL Tree: After insertion or deletion operations, an AVL tree performs rotation adjustments based on the balance factor of nodes to restore the tree's balance. These rotations can be left rotations, right rotations, left-right rotations, or right-left rotations, performed as needed.
391
- *
392
- * Use Cases and Efficiency:
393
- * Perfectly Balanced Binary Tree: Perfectly balanced binary trees are typically used in specific scenarios such as complete binary heaps in heap sort or certain types of Huffman trees. However, they are not suitable for dynamic operations requiring frequent insertions and deletions, as these operations often necessitate full tree reconstruction.
394
- * AVL Tree: AVL trees are well-suited for scenarios involving frequent searching, insertion, and deletion operations. Through rotation adjustments, AVL trees maintain their balance, ensuring average and worst-case time complexity of O(log n).
395
- */
396
- /**
397
- * The `perfectlyBalance` function takes a binary tree, performs a depth-first search to sort the nodes, and then
398
- * constructs a balanced binary search tree using either a recursive or iterative approach.
399
- * @returns The function `perfectlyBalance()` returns a boolean value.
400
- */
401
- BST.prototype.perfectlyBalance = function () {
402
- var _this = this;
403
- var sorted = this.DFS('in', 'node'), n = sorted.length;
404
- this.clear();
405
- if (sorted.length < 1)
406
- return false;
407
- if (this.loopType === data_structure_typed_1.LoopType.RECURSIVE) {
408
- var buildBalanceBST_1 = function (l, r) {
409
- if (l > r)
410
- return;
411
- var m = l + Math.floor((r - l) / 2);
412
- var midNode = sorted[m];
413
- _this.add(midNode.id, midNode.val);
414
- buildBalanceBST_1(l, m - 1);
415
- buildBalanceBST_1(m + 1, r);
416
- };
417
- buildBalanceBST_1(0, n - 1);
418
- return true;
419
- }
420
- else {
421
- var stack = [[0, n - 1]];
422
- while (stack.length > 0) {
423
- var popped = stack.pop();
424
- if (popped) {
425
- var _a = __read(popped, 2), l = _a[0], r = _a[1];
426
- if (l <= r) {
427
- var m = l + Math.floor((r - l) / 2);
428
- var midNode = sorted[m];
429
- this.add(midNode.id, midNode.val);
430
- stack.push([m + 1, r]);
431
- stack.push([l, m - 1]);
432
- }
433
- }
434
- }
435
- return true;
436
- }
437
- };
438
- /**
439
- * The function `isAVLBalanced` checks if a binary tree is balanced according to the AVL tree property.
440
- * @returns a boolean value.
441
- */
442
- BST.prototype.isAVLBalanced = function () {
443
- var _a, _b;
444
- if (!this.root)
445
- return true;
446
- var balanced = true;
447
- if (this.loopType === data_structure_typed_1.LoopType.RECURSIVE) {
448
- var _height_1 = function (cur) {
449
- if (!cur)
450
- return 0;
451
- var leftHeight = _height_1(cur.left), rightHeight = _height_1(cur.right);
452
- if (Math.abs(leftHeight - rightHeight) > 1)
453
- balanced = false;
454
- return Math.max(leftHeight, rightHeight) + 1;
455
- };
456
- _height_1(this.root);
457
- }
458
- else {
459
- var stack = [];
460
- var node = this.root, last = null;
461
- var depths = new Map();
462
- while (stack.length > 0 || node) {
463
- if (node) {
464
- stack.push(node);
465
- node = node.left;
466
- }
467
- else {
468
- node = stack[stack.length - 1];
469
- if (!node.right || last === node.right) {
470
- node = stack.pop();
471
- if (node) {
472
- var left = node.left ? (_a = depths.get(node.left)) !== null && _a !== void 0 ? _a : -1 : -1;
473
- var right = node.right ? (_b = depths.get(node.right)) !== null && _b !== void 0 ? _b : -1 : -1;
474
- if (Math.abs(left - right) > 1)
475
- return false;
476
- depths.set(node, 1 + Math.max(left, right));
477
- last = node;
478
- node = null;
479
- }
480
- }
481
- else
482
- node = node.right;
483
- }
484
- }
485
- }
486
- return balanced;
487
- };
488
- /**
489
- * The function compares two binary tree node IDs using a comparator function and returns whether the first ID is
490
- * greater than, less than, or equal to the second ID.
491
- * @param {BinaryTreeNodeId} a - a is a BinaryTreeNodeId, which represents the identifier of a binary tree node.
492
- * @param {BinaryTreeNodeId} b - The parameter "b" in the above code refers to a BinaryTreeNodeId.
493
- * @returns a value of type CP (ComparisonResult). The possible return values are CP.gt (greater than), CP.lt (less
494
- * than), or CP.eq (equal).
495
- */
496
- BST.prototype._compare = function (a, b) {
497
- var compared = this._comparator(a, b);
498
- if (compared > 0)
499
- return data_structure_typed_1.CP.gt;
500
- else if (compared < 0)
501
- return data_structure_typed_1.CP.lt;
502
- else
503
- return data_structure_typed_1.CP.eq;
504
- };
505
- return BST;
506
- }(data_structure_typed_1.BinaryTree));
507
- exports.BST = BST;