data-structure-typed 1.15.1 → 1.16.1

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.
Files changed (224) hide show
  1. package/README.md +398 -27
  2. package/dist/data-structures/binary-tree/binary-tree.d.ts +30 -30
  3. package/dist/data-structures/binary-tree/binary-tree.js +55 -55
  4. package/dist/data-structures/binary-tree/segment-tree.d.ts +17 -17
  5. package/dist/data-structures/binary-tree/segment-tree.js +30 -30
  6. package/dist/data-structures/graph/abstract-graph.d.ts +6 -6
  7. package/dist/data-structures/graph/abstract-graph.js +6 -6
  8. package/dist/data-structures/graph/directed-graph.d.ts +4 -4
  9. package/dist/data-structures/graph/directed-graph.js +6 -6
  10. package/dist/data-structures/graph/undirected-graph.d.ts +3 -3
  11. package/dist/data-structures/hash/coordinate-map.d.ts +2 -2
  12. package/dist/data-structures/hash/coordinate-set.d.ts +2 -2
  13. package/dist/data-structures/heap/heap.d.ts +40 -25
  14. package/dist/data-structures/heap/heap.js +72 -27
  15. package/dist/data-structures/heap/max-heap.d.ts +3 -3
  16. package/dist/data-structures/heap/min-heap.d.ts +3 -3
  17. package/dist/data-structures/index.d.ts +1 -0
  18. package/dist/data-structures/index.js +1 -0
  19. package/dist/data-structures/linked-list/doubly-linked-list.d.ts +9 -9
  20. package/dist/data-structures/linked-list/doubly-linked-list.js +12 -12
  21. package/dist/data-structures/linked-list/singly-linked-list.d.ts +7 -7
  22. package/dist/data-structures/priority-queue/max-priority-queue.d.ts +4 -5
  23. package/dist/data-structures/priority-queue/max-priority-queue.js +30 -6
  24. package/dist/data-structures/priority-queue/min-priority-queue.d.ts +4 -5
  25. package/dist/data-structures/priority-queue/min-priority-queue.js +31 -6
  26. package/dist/data-structures/priority-queue/priority-queue.d.ts +20 -9
  27. package/dist/data-structures/priority-queue/priority-queue.js +34 -28
  28. package/dist/data-structures/queue/deque.d.ts +1 -1
  29. package/dist/data-structures/tree/index.d.ts +1 -0
  30. package/dist/data-structures/tree/index.js +17 -0
  31. package/dist/data-structures/tree/tree.d.ts +9 -0
  32. package/dist/data-structures/tree/tree.js +52 -0
  33. package/dist/data-structures/types/heap.d.ts +0 -4
  34. package/dist/utils/types/utils.d.ts +1 -3
  35. package/dist/utils/types/utils.js +0 -14
  36. package/dist/utils/utils.js +0 -197
  37. package/docs/.nojekyll +1 -0
  38. package/docs/assets/highlight.css +92 -0
  39. package/docs/assets/main.js +58 -0
  40. package/docs/assets/search.js +1 -0
  41. package/docs/assets/style.css +1367 -0
  42. package/docs/classes/AVLTree.html +2192 -0
  43. package/docs/classes/AVLTreeNode.html +574 -0
  44. package/docs/classes/AaTree.html +150 -0
  45. package/docs/classes/AbstractEdge.html +269 -0
  46. package/docs/classes/AbstractGraph.html +927 -0
  47. package/docs/classes/AbstractVertex.html +215 -0
  48. package/docs/classes/ArrayDeque.html +417 -0
  49. package/docs/classes/BST.html +2038 -0
  50. package/docs/classes/BSTNode.html +570 -0
  51. package/docs/classes/BTree.html +150 -0
  52. package/docs/classes/BinaryIndexedTree.html +289 -0
  53. package/docs/classes/BinaryTree.html +1827 -0
  54. package/docs/classes/BinaryTreeNode.html +533 -0
  55. package/docs/classes/Character.html +198 -0
  56. package/docs/classes/CoordinateMap.html +469 -0
  57. package/docs/classes/CoordinateSet.html +430 -0
  58. package/docs/classes/Deque.html +767 -0
  59. package/docs/classes/DirectedEdge.html +354 -0
  60. package/docs/classes/DirectedGraph.html +1243 -0
  61. package/docs/classes/DirectedVertex.html +226 -0
  62. package/docs/classes/DoublyLinkedList.html +733 -0
  63. package/docs/classes/DoublyLinkedListNode.html +258 -0
  64. package/docs/classes/Heap.html +482 -0
  65. package/docs/classes/HeapItem.html +233 -0
  66. package/docs/classes/Matrix2D.html +480 -0
  67. package/docs/classes/MatrixNTI2D.html +218 -0
  68. package/docs/classes/MaxHeap.html +500 -0
  69. package/docs/classes/MaxPriorityQueue.html +809 -0
  70. package/docs/classes/MinHeap.html +501 -0
  71. package/docs/classes/MinPriorityQueue.html +811 -0
  72. package/docs/classes/Navigator.html +291 -0
  73. package/docs/classes/ObjectDeque.html +423 -0
  74. package/docs/classes/PriorityQueue.html +733 -0
  75. package/docs/classes/Queue.html +370 -0
  76. package/docs/classes/RBTree.html +150 -0
  77. package/docs/classes/SegmentTree.html +345 -0
  78. package/docs/classes/SegmentTreeNode.html +418 -0
  79. package/docs/classes/SinglyLinkedList.html +1105 -0
  80. package/docs/classes/SinglyLinkedListNode.html +375 -0
  81. package/docs/classes/SplayTree.html +150 -0
  82. package/docs/classes/Stack.html +346 -0
  83. package/docs/classes/TreeMultiSet.html +2036 -0
  84. package/docs/classes/TreeNode.html +236 -0
  85. package/docs/classes/Trie.html +350 -0
  86. package/docs/classes/TrieNode.html +258 -0
  87. package/docs/classes/TwoThreeTree.html +150 -0
  88. package/docs/classes/UndirectedEdge.html +313 -0
  89. package/docs/classes/UndirectedGraph.html +1080 -0
  90. package/docs/classes/UndirectedVertex.html +226 -0
  91. package/docs/classes/Vector2D.html +783 -0
  92. package/docs/enums/CP.html +159 -0
  93. package/docs/enums/FamilyPosition.html +159 -0
  94. package/docs/enums/LoopType.html +160 -0
  95. package/docs/index.html +494 -0
  96. package/docs/interfaces/AVLTreeDeleted.html +161 -0
  97. package/docs/interfaces/BinaryTreeNodeObj.html +168 -0
  98. package/docs/interfaces/HeapOptions.html +167 -0
  99. package/docs/interfaces/IDirectedGraph.html +243 -0
  100. package/docs/interfaces/IGraph.html +427 -0
  101. package/docs/interfaces/NavigatorParams.html +197 -0
  102. package/docs/interfaces/PriorityQueueOptions.html +168 -0
  103. package/docs/modules.html +218 -0
  104. package/docs/types/BSTComparator.html +140 -0
  105. package/docs/types/BSTDeletedResult.html +137 -0
  106. package/docs/types/BinaryTreeDeleted.html +137 -0
  107. package/docs/types/BinaryTreeNodeId.html +125 -0
  108. package/docs/types/BinaryTreeNodePropertyName.html +125 -0
  109. package/docs/types/DFSOrderPattern.html +125 -0
  110. package/docs/types/DijkstraResult.html +145 -0
  111. package/docs/types/Direction.html +125 -0
  112. package/docs/types/DoublyLinkedListGetBy.html +125 -0
  113. package/docs/types/NodeOrPropertyName.html +125 -0
  114. package/docs/types/PriorityQueueComparator.html +145 -0
  115. package/docs/types/PriorityQueueDFSOrderPattern.html +125 -0
  116. package/docs/types/ResultByProperty.html +130 -0
  117. package/docs/types/ResultsByProperty.html +130 -0
  118. package/docs/types/SegmentTreeNodeVal.html +125 -0
  119. package/docs/types/SpecifyOptional.html +132 -0
  120. package/docs/types/Thunk.html +133 -0
  121. package/docs/types/ToThunkFn.html +133 -0
  122. package/docs/types/TopologicalStatus.html +125 -0
  123. package/docs/types/TreeMultiSetDeletedResult.html +137 -0
  124. package/docs/types/TrlAsyncFn.html +138 -0
  125. package/docs/types/TrlFn.html +138 -0
  126. package/docs/types/Turning.html +125 -0
  127. package/docs/types/VertexId.html +125 -0
  128. package/{tests/unit/data-structures/binary-tree → notes}/bst.test.ts +11 -15
  129. package/notes/note.md +23 -0
  130. package/package.json +2 -4
  131. package/.idea/data-structure-typed.iml +0 -14
  132. package/.idea/modules.xml +0 -8
  133. package/.idea/vcs.xml +0 -6
  134. package/src/assets/complexities-diff.jpg +0 -0
  135. package/src/assets/data-structure-complexities.jpg +0 -0
  136. package/src/assets/logo.png +0 -0
  137. package/src/data-structures/binary-tree/aa-tree.ts +0 -3
  138. package/src/data-structures/binary-tree/avl-tree.ts +0 -293
  139. package/src/data-structures/binary-tree/b-tree.ts +0 -3
  140. package/src/data-structures/binary-tree/binary-indexed-tree.ts +0 -69
  141. package/src/data-structures/binary-tree/binary-tree.ts +0 -1485
  142. package/src/data-structures/binary-tree/bst.ts +0 -497
  143. package/src/data-structures/binary-tree/diagrams/avl-tree-inserting.gif +0 -0
  144. package/src/data-structures/binary-tree/diagrams/bst-rotation.gif +0 -0
  145. package/src/data-structures/binary-tree/diagrams/segment-tree.png +0 -0
  146. package/src/data-structures/binary-tree/index.ts +0 -11
  147. package/src/data-structures/binary-tree/rb-tree.ts +0 -3
  148. package/src/data-structures/binary-tree/segment-tree.ts +0 -248
  149. package/src/data-structures/binary-tree/splay-tree.ts +0 -3
  150. package/src/data-structures/binary-tree/tree-multiset.ts +0 -53
  151. package/src/data-structures/binary-tree/two-three-tree.ts +0 -3
  152. package/src/data-structures/diagrams/README.md +0 -5
  153. package/src/data-structures/graph/abstract-graph.ts +0 -956
  154. package/src/data-structures/graph/diagrams/adjacency-list-pros-cons.jpg +0 -0
  155. package/src/data-structures/graph/diagrams/adjacency-list.jpg +0 -0
  156. package/src/data-structures/graph/diagrams/adjacency-matrix-pros-cons.jpg +0 -0
  157. package/src/data-structures/graph/diagrams/adjacency-matrix.jpg +0 -0
  158. package/src/data-structures/graph/diagrams/dfs-can-do.jpg +0 -0
  159. package/src/data-structures/graph/diagrams/edge-list-pros-cons.jpg +0 -0
  160. package/src/data-structures/graph/diagrams/edge-list.jpg +0 -0
  161. package/src/data-structures/graph/diagrams/max-flow.jpg +0 -0
  162. package/src/data-structures/graph/diagrams/mst.jpg +0 -0
  163. package/src/data-structures/graph/diagrams/tarjan-articulation-point-bridge.png +0 -0
  164. package/src/data-structures/graph/diagrams/tarjan-complicate-simple.png +0 -0
  165. package/src/data-structures/graph/diagrams/tarjan-strongly-connected-component.png +0 -0
  166. package/src/data-structures/graph/diagrams/tarjan.mp4 +0 -0
  167. package/src/data-structures/graph/diagrams/tarjan.webp +0 -0
  168. package/src/data-structures/graph/directed-graph.ts +0 -424
  169. package/src/data-structures/graph/index.ts +0 -3
  170. package/src/data-structures/graph/undirected-graph.ts +0 -254
  171. package/src/data-structures/hash/coordinate-map.ts +0 -71
  172. package/src/data-structures/hash/coordinate-set.ts +0 -60
  173. package/src/data-structures/hash/hash-table.ts +0 -1
  174. package/src/data-structures/hash/index.ts +0 -6
  175. package/src/data-structures/hash/pair.ts +0 -1
  176. package/src/data-structures/hash/tree-map.ts +0 -1
  177. package/src/data-structures/hash/tree-set.ts +0 -1
  178. package/src/data-structures/heap/heap.ts +0 -156
  179. package/src/data-structures/heap/index.ts +0 -3
  180. package/src/data-structures/heap/max-heap.ts +0 -31
  181. package/src/data-structures/heap/min-heap.ts +0 -34
  182. package/src/data-structures/index.ts +0 -13
  183. package/src/data-structures/linked-list/doubly-linked-list.ts +0 -351
  184. package/src/data-structures/linked-list/index.ts +0 -2
  185. package/src/data-structures/linked-list/singly-linked-list.ts +0 -748
  186. package/src/data-structures/linked-list/skip-linked-list.ts +0 -1
  187. package/src/data-structures/matrix/index.ts +0 -4
  188. package/src/data-structures/matrix/matrix.ts +0 -27
  189. package/src/data-structures/matrix/matrix2d.ts +0 -208
  190. package/src/data-structures/matrix/navigator.ts +0 -122
  191. package/src/data-structures/matrix/vector2d.ts +0 -316
  192. package/src/data-structures/priority-queue/index.ts +0 -3
  193. package/src/data-structures/priority-queue/max-priority-queue.ts +0 -24
  194. package/src/data-structures/priority-queue/min-priority-queue.ts +0 -24
  195. package/src/data-structures/priority-queue/priority-queue.ts +0 -346
  196. package/src/data-structures/queue/deque.ts +0 -241
  197. package/src/data-structures/queue/index.ts +0 -2
  198. package/src/data-structures/queue/queue.ts +0 -120
  199. package/src/data-structures/stack/index.ts +0 -1
  200. package/src/data-structures/stack/stack.ts +0 -98
  201. package/src/data-structures/trie/index.ts +0 -1
  202. package/src/data-structures/trie/trie.ts +0 -225
  203. package/src/data-structures/types/abstract-graph.ts +0 -51
  204. package/src/data-structures/types/avl-tree.ts +0 -6
  205. package/src/data-structures/types/binary-tree.ts +0 -15
  206. package/src/data-structures/types/bst.ts +0 -5
  207. package/src/data-structures/types/directed-graph.ts +0 -18
  208. package/src/data-structures/types/doubly-linked-list.ts +0 -1
  209. package/src/data-structures/types/heap.ts +0 -8
  210. package/src/data-structures/types/index.ts +0 -13
  211. package/src/data-structures/types/navigator.ts +0 -13
  212. package/src/data-structures/types/priority-queue.ts +0 -9
  213. package/src/data-structures/types/segment-tree.ts +0 -1
  214. package/src/data-structures/types/singly-linked-list.ts +0 -1
  215. package/src/data-structures/types/tree-multiset.ts +0 -3
  216. package/src/index.ts +0 -1
  217. package/src/utils/index.ts +0 -2
  218. package/src/utils/types/index.ts +0 -1
  219. package/src/utils/types/utils.ts +0 -176
  220. package/src/utils/utils.ts +0 -290
  221. package/tests/unit/data-structures/graph/abstract-graph.ts +0 -0
  222. package/tests/unit/data-structures/graph/directed-graph.test.ts +0 -495
  223. package/tests/unit/data-structures/graph/index.ts +0 -3
  224. package/tests/unit/data-structures/graph/undirected-graph.ts +0 -0
@@ -1,1485 +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
-
9
- import {trampoline} from '../../utils';
10
- import type {
11
- BinaryTreeDeleted,
12
- BinaryTreeNodeId,
13
- BinaryTreeNodePropertyName,
14
- DFSOrderPattern,
15
- NodeOrPropertyName,
16
- ResultByProperty,
17
- ResultsByProperty
18
- } from '../types';
19
-
20
- /* This enumeration defines the position of a node within a family tree composed of three associated nodes, where 'root' represents the root node of the family tree, 'left' represents the left child node, and 'right' represents the right child node. */
21
- export enum FamilyPosition {root, left, right}
22
-
23
- /**
24
- * Enum representing different loop types.
25
- *
26
- * - `iterative`: Indicates the iterative loop type (with loops that use iterations).
27
- * - `recursive`: Indicates the recursive loop type (with loops that call themselves).
28
- */
29
- export enum LoopType { iterative = 1, recursive = 2}
30
-
31
- export class BinaryTreeNode<T> {
32
-
33
- protected _id: BinaryTreeNodeId;
34
- get id(): BinaryTreeNodeId {
35
- return this._id;
36
- }
37
-
38
- /**
39
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
40
- */
41
- getId(): BinaryTreeNodeId {
42
- return this._id;
43
- }
44
-
45
- set id(v: BinaryTreeNodeId) {
46
- this._id = v;
47
- }
48
-
49
- protected _val: T;
50
- get val(): T {
51
- return this._val;
52
- }
53
-
54
- /**
55
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
56
- */
57
- getVal(): T {
58
- return this._val;
59
- }
60
-
61
- set val(v: T) {
62
- this._val = v;
63
- }
64
-
65
- protected _left?: BinaryTreeNode<T> | null;
66
- get left(): BinaryTreeNode<T> | null | undefined {
67
- return this._left;
68
- }
69
-
70
- /**
71
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
72
- */
73
- getLeft(): BinaryTreeNode<T> | null | undefined {
74
- return this._left;
75
- }
76
-
77
- set left(v: BinaryTreeNode<T> | null | undefined) {
78
- if (v) {
79
- v.parent = this;
80
- v.familyPosition = FamilyPosition.left;
81
- }
82
- this._left = v;
83
- }
84
-
85
- protected _right?: BinaryTreeNode<T> | null;
86
- get right(): BinaryTreeNode<T> | null | undefined {
87
- return this._right;
88
- }
89
-
90
- /**
91
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
92
- */
93
- getRight(): BinaryTreeNode<T> | null | undefined {
94
- return this._right;
95
- }
96
-
97
- set right(v: BinaryTreeNode<T> | null | undefined) {
98
- if (v) {
99
- v.parent = this;
100
- v.familyPosition = FamilyPosition.right;
101
- }
102
- this._right = v;
103
- }
104
-
105
- protected _parent: BinaryTreeNode<T> | null | undefined;
106
- get parent(): BinaryTreeNode<T> | null | undefined {
107
- return this._parent;
108
- }
109
-
110
- /**
111
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
112
- */
113
- getParent(): BinaryTreeNode<T> | null | undefined {
114
- return this._parent;
115
- }
116
-
117
- set parent(v: BinaryTreeNode<T> | null | undefined) {
118
- this._parent = v;
119
- }
120
-
121
- protected _familyPosition: FamilyPosition = FamilyPosition.root;
122
- get familyPosition(): FamilyPosition {
123
- return this._familyPosition;
124
- }
125
-
126
- /**
127
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
128
- */
129
- getFamilyPosition(): FamilyPosition {
130
- return this._familyPosition;
131
- }
132
-
133
- set familyPosition(v: FamilyPosition) {
134
- this._familyPosition = v;
135
- }
136
-
137
- protected _count = 1;
138
- get count(): number {
139
- return this._count;
140
- }
141
-
142
- /**
143
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
144
- */
145
- getCount(): number {
146
- return this._count;
147
- }
148
-
149
- set count(v: number) {
150
- this._count = v;
151
- }
152
-
153
- protected _height = 0;
154
- get height(): number {
155
- return this._height;
156
- }
157
-
158
- /**
159
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
160
- */
161
- getHeight(): number {
162
- return this._height;
163
- }
164
-
165
- set height(v: number) {
166
- this._height = v;
167
- }
168
-
169
- constructor(id: BinaryTreeNodeId, val: T, count?: number) {
170
- this._id = id;
171
- this._val = val;
172
- this._count = count ?? 1;
173
- }
174
-
175
- swapLocation(swapNode: BinaryTreeNode<T>): BinaryTreeNode<T> {
176
- const {val, count, height} = swapNode;
177
- const tempNode = new BinaryTreeNode<T>(swapNode.id, val);
178
- tempNode.val = val;
179
- tempNode.count = count;
180
- tempNode.height = height;
181
-
182
- swapNode.id = this.id;
183
- swapNode.val = this.val;
184
- swapNode.count = this.count;
185
- swapNode.height = this.height;
186
-
187
- this.id = tempNode.id;
188
- this.val = tempNode.val;
189
- this.count = tempNode.count;
190
- this.height = tempNode.height;
191
- return swapNode;
192
- }
193
-
194
- clone(): BinaryTreeNode<T> {
195
- return new BinaryTreeNode<T>(this.id, this.val, this.count);
196
- }
197
- }
198
-
199
- export class BinaryTree<T> {
200
- protected _loopType: LoopType = LoopType.iterative;
201
- protected _visitedId: BinaryTreeNodeId[] = [];
202
- protected _visitedVal: Array<T> = [];
203
- protected _visitedNode: BinaryTreeNode<T>[] = [];
204
- protected _visitedCount: number[] = [];
205
- protected _visitedLeftSum: number[] = [];
206
- private readonly _autoIncrementId: boolean = false;
207
- private _maxId: number = -1;
208
- private readonly _isDuplicatedVal: boolean = false;
209
-
210
- /**
211
- * The constructor function accepts an optional options object and sets the values of loopType, autoIncrementId, and
212
- * isDuplicatedVal based on the provided options.
213
- * @param [options] - An optional object that can contain the following properties:
214
- */
215
- constructor(options?: {
216
- loopType?: LoopType,
217
- autoIncrementId?: boolean,
218
- isDuplicatedVal?: boolean
219
- }) {
220
- if (options !== undefined) {
221
- const {
222
- loopType = LoopType.iterative,
223
- autoIncrementId = false,
224
- isDuplicatedVal = false
225
- } = options;
226
- this._isDuplicatedVal = isDuplicatedVal;
227
- this._autoIncrementId = autoIncrementId;
228
- this._loopType = loopType;
229
- }
230
- }
231
-
232
- protected _root: BinaryTreeNode<T> | null = null;
233
-
234
- get root(): BinaryTreeNode<T> | null {
235
- return this._root;
236
- }
237
-
238
- /**
239
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Getters (using the same name as the property) while utilizing separate method names for Setters.
240
- * @returns The method is returning either a BinaryTreeNode object of type T or null.
241
- */
242
- getRoot(): BinaryTreeNode<T> | null {
243
- return this._root;
244
- }
245
-
246
- protected set root(v: BinaryTreeNode<T> | null) {
247
- if (v) {
248
- v.parent = null;
249
- v.familyPosition = FamilyPosition.root;
250
- }
251
- this._root = v;
252
- }
253
-
254
- protected _size = 0;
255
-
256
- get size(): number {
257
- return this._size;
258
- }
259
-
260
- /**
261
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
262
- */
263
- getSize(): number {
264
- return this._size;
265
- }
266
-
267
- protected set size(v: number) {
268
- this._size = v;
269
- }
270
-
271
- protected _count = 0;
272
-
273
- get count(): number {
274
- return this._count;
275
- }
276
-
277
- /**
278
- * Starting from TypeScript version 5.0 and onwards, the use of distinct access modifiers for Getters and Setters is not permitted. As an alternative, to ensure compatibility, it is necessary to adopt a Java-style approach for Setters (using the same name as the property) while utilizing separate method names for Getters.
279
- */
280
- getCount(): number {
281
- return this._count;
282
- }
283
-
284
- protected set count(v: number) {
285
- this._count = v;
286
- }
287
-
288
- /**
289
- * The function creates a new binary tree node with the given id, value, and count, or returns null if the value is
290
- * null.
291
- * @param {BinaryTreeNodeId} id - The `id` parameter is the identifier for the binary tree node. It is of type
292
- * `BinaryTreeNodeId`, which could be a string or a number, depending on how you want to identify your nodes.
293
- * @param {T | null} val - The `val` parameter represents the value to be stored in the binary tree node. It can be of
294
- * any type `T` or `null`.
295
- * @param {number} [count] - The count parameter is an optional parameter that represents the number of occurrences of
296
- * the value in the binary tree node. It is of type number.
297
- * @returns The function `createNode` returns a `BinaryTreeNode<T>` object if the `val` parameter is not null.
298
- * Otherwise, it returns null.
299
- */
300
- createNode(id: BinaryTreeNodeId, val: T | null, count?: number): BinaryTreeNode<T> | null {
301
- return val !== null ? new BinaryTreeNode(id, val, count) : null;
302
- }
303
-
304
- /**
305
- * The clear function resets the state of an object by setting its properties to their initial values.
306
- */
307
- clear() {
308
- this.root = null;
309
- this.size = 0;
310
- this.count = 0;
311
- this._maxId = -1;
312
- }
313
-
314
- /**
315
- * The function checks if the size of an object is equal to zero and returns a boolean value.
316
- * @returns A boolean value indicating whether the size of the object is 0 or not.
317
- */
318
- isEmpty(): boolean {
319
- return this.size === 0;
320
- }
321
-
322
- /**
323
- * The `add` function inserts a new node with a given ID and value into a binary tree, updating the count if the node
324
- * already exists.
325
- * @param {BinaryTreeNodeId} id - The id parameter is the identifier of the binary tree node. It is used to uniquely
326
- * identify each node in the binary tree.
327
- * @param {T} val - The value to be inserted into the binary tree.
328
- * @param {number} [count] - The `count` parameter is an optional parameter that specifies the number of times the
329
- * value should be inserted into the binary tree. If not provided, it defaults to 1.
330
- * @returns The function `add` returns a `BinaryTreeNode<T>` object if a new node is inserted, or `null` if no new node
331
- * is inserted, or `undefined` if the insertion fails.
332
- */
333
- add(id: BinaryTreeNodeId, val: T, count?: number): BinaryTreeNode<T> | null | undefined {
334
- count = count ?? 1;
335
-
336
- const _bfs = (root: BinaryTreeNode<T>, newNode: BinaryTreeNode<T> | null): BinaryTreeNode<T> | undefined | null => {
337
- const queue: Array<BinaryTreeNode<T> | null> = [root];
338
- while (queue.length > 0) {
339
- const cur = queue.shift();
340
- if (cur) {
341
- const inserted = this.addTo(newNode, cur);
342
- if (inserted !== undefined) return inserted;
343
- if (cur.left) queue.push(cur.left);
344
- if (cur.right) queue.push(cur.right);
345
- } else return;
346
- }
347
- return;
348
- };
349
-
350
- let inserted: BinaryTreeNode<T> | null | undefined;
351
- const needInsert = val !== null ? new BinaryTreeNode<T>(id, val, count) : null;
352
- const existNode = val !== null ? this.get(id, 'id') : null;
353
- if (this.root) {
354
- if (existNode) {
355
- existNode.count += count;
356
- existNode.val = val;
357
- if (needInsert !== null) {
358
- this.count += count;
359
- inserted = existNode;
360
- }
361
- } else {
362
- inserted = _bfs(this.root, needInsert);
363
- }
364
- } else {
365
- this.root = val !== null ? new BinaryTreeNode<T>(id, val, count) : null;
366
- if (needInsert !== null) {
367
- this.size = 1;
368
- this.count = count;
369
- }
370
- inserted = this.root;
371
- }
372
- return inserted;
373
- }
374
-
375
- /**
376
- * The function inserts a new node into a binary tree as the left or right child of a given parent node.
377
- * @param {BinaryTreeNode<T> | null} newNode - The `newNode` parameter is an instance of the `BinaryTreeNode` class or
378
- * `null`. It represents the node that needs to be inserted into the binary tree.
379
- * @param parent - The `parent` parameter is a BinaryTreeNode object representing the parent node to which the new node
380
- * will be inserted as a child.
381
- * @returns The method returns the newly inserted node, either as the left child or the right child of the parent node.
382
- */
383
- addTo(newNode: BinaryTreeNode<T> | null, parent: BinaryTreeNode<T>) {
384
- if (parent) {
385
- if (parent.left === undefined) {
386
- if (newNode) {
387
- newNode.parent = parent;
388
- newNode.familyPosition = FamilyPosition.left;
389
- }
390
- parent.left = newNode;
391
- if (newNode !== null) {
392
- this.size++;
393
- this.count += newNode?.count ?? 0;
394
- }
395
-
396
- return parent.left;
397
- } else if (parent.right === undefined) {
398
- if (newNode) {
399
- newNode.parent = parent;
400
- newNode.familyPosition = FamilyPosition.right;
401
- }
402
- parent.right = newNode;
403
- if (newNode !== null) {
404
- this.size++;
405
- this.count += newNode?.count ?? 0;
406
- }
407
- return parent.right;
408
- } else {
409
- return;
410
- }
411
- } else {
412
- return;
413
- }
414
- }
415
-
416
- /**
417
- * The `addMany` function inserts multiple items into a binary tree and returns an array of the inserted nodes or
418
- * null/undefined values.
419
- * @param {T[] | BinaryTreeNode<T>[]} data - The `data` parameter can be either an array of elements of type `T` or an
420
- * array of `BinaryTreeNode<T>` objects.
421
- * @returns The function `addMany` returns an array of `BinaryTreeNode<T>`, `null`, or `undefined` values.
422
- */
423
- addMany(data: T[] | BinaryTreeNode<T>[]): (BinaryTreeNode<T> | null | undefined)[] {
424
- const inserted: (BinaryTreeNode<T> | null | undefined)[] = [];
425
- const map: Map<T | BinaryTreeNode<T>, number> = new Map();
426
-
427
- if (!this._isDuplicatedVal) {
428
- for (const i of data) map.set(i, (map.get(i) ?? 0) + 1);
429
- }
430
-
431
- for (const item of data) {
432
- const count = this._isDuplicatedVal ? 1 : map.get(item);
433
-
434
- if (item instanceof BinaryTreeNode) {
435
- inserted.push(this.add(item.id, item.val, item.count));
436
- } else if (typeof item === 'number' && !this._autoIncrementId) {
437
- if (!this._isDuplicatedVal) {
438
- if (map.get(item) !== undefined) {
439
- inserted.push(this.add(item, item, count));
440
- map.delete(item);
441
- }
442
- } else {
443
- inserted.push(this.add(item, item, 1));
444
- }
445
- } else {
446
- if (item !== null) {
447
- if (!this._isDuplicatedVal) {
448
- if (map.get(item) !== undefined) {
449
- inserted.push(this.add(++this._maxId, item, count));
450
- map.delete(item);
451
- }
452
- } else {
453
- inserted.push(this.add(++this._maxId, item, 1));
454
- }
455
- } else {
456
- inserted.push(this.add(Number.MAX_SAFE_INTEGER, item, 0));
457
- }
458
- }
459
- }
460
- return inserted;
461
- }
462
-
463
- /**
464
- * The `fill` function clears the current data and inserts new data, returning a boolean indicating if the insertion
465
- * was successful.
466
- * @param {T[] | BinaryTreeNode<T>[]} data - The `data` parameter can be either an array of elements of type `T` or an
467
- * array of `BinaryTreeNode<T>` objects.
468
- * @returns The method is returning a boolean value.
469
- */
470
- fill(data: T[] | BinaryTreeNode<T>[]): boolean {
471
- this.clear();
472
- return data.length === this.addMany(data).length;
473
- }
474
-
475
- /**
476
- * The function removes a node from a binary tree and returns information about the deleted node.
477
- * @param {BinaryTreeNodeId} id - The `id` parameter is the identifier of the binary tree node that you want to remove.
478
- * It is of type `BinaryTreeNodeId`.
479
- * @param {boolean} [ignoreCount] - The `ignoreCount` parameter is an optional boolean parameter that determines
480
- * whether to ignore the count of the node being removed. If `ignoreCount` is set to `true`, the count of the node will
481
- * not be decremented and the overall count of the binary tree will not be updated. If `
482
- * @returns An array of objects is being returned. Each object in the array has two properties: "deleted" and
483
- * "needBalanced". The "deleted" property contains the deleted node or undefined if no node was deleted. The
484
- * "needBalanced" property is always null.
485
- */
486
- remove(id: BinaryTreeNodeId, ignoreCount?: boolean): BinaryTreeDeleted<T>[] {
487
- const nodes = this.getNodes(id, 'id', true);
488
- let node: BinaryTreeNode<T> | null | undefined = nodes[0];
489
-
490
- if (!node) node = undefined;
491
- else if (node.count > 1 && !ignoreCount) {
492
- node.count--;
493
- this.count--;
494
- } else if (node instanceof BinaryTreeNode) {
495
- const [subSize, subCount] = this.getSubTreeSizeAndCount(node);
496
-
497
- switch (node.familyPosition) {
498
- case 0:
499
- this.size -= subSize;
500
- this.count -= subCount;
501
- node = undefined;
502
- break;
503
- case 1:
504
- if (node.parent) {
505
- this.size -= subSize;
506
- this.count -= subCount;
507
- node.parent.left = null;
508
- }
509
- break;
510
- case 2:
511
- if (node.parent) {
512
- this.size -= subSize;
513
- this.count -= subCount;
514
- node.parent.right = null;
515
- }
516
- break;
517
- }
518
- }
519
- return [{deleted: node, needBalanced: null}];
520
- }
521
-
522
- /**
523
- * The function calculates the depth of a binary tree node by traversing its parent nodes.
524
- * @param node - BinaryTreeNode<T> - This is the node for which we want to calculate the depth. It is a generic type,
525
- * meaning it can represent any type of data that we want to store in the node.
526
- * @returns The depth of the given binary tree node.
527
- */
528
- getDepth(node: BinaryTreeNode<T>): number {
529
- let depth = 0;
530
- while (node.parent) {
531
- depth++;
532
- node = node.parent;
533
- }
534
- return depth;
535
- }
536
-
537
- /**
538
- * The `getHeight` function calculates the maximum height of a binary tree using either a recursive or iterative
539
- * approach.
540
- * @param {BinaryTreeNode<T> | null} [beginRoot] - The `beginRoot` parameter is an optional parameter of type
541
- * `BinaryTreeNode<T> | null`. It represents the starting node from which to calculate the height of the binary tree.
542
- * If no value is provided for `beginRoot`, the function will use the `root` property of the class instance as
543
- * @returns the height of the binary tree.
544
- */
545
- getHeight(beginRoot?: BinaryTreeNode<T> | null): number {
546
- beginRoot = beginRoot ?? this.root;
547
- if (!beginRoot) return -1;
548
-
549
- if (this._loopType === LoopType.recursive) {
550
- const _getMaxHeight = (cur: BinaryTreeNode<T> | null | undefined): number => {
551
- if (!cur) return -1;
552
- const leftHeight = _getMaxHeight(cur.left);
553
- const rightHeight = _getMaxHeight(cur.right);
554
- return Math.max(leftHeight, rightHeight) + 1;
555
- };
556
-
557
- return _getMaxHeight(beginRoot);
558
- } else {
559
- const stack: BinaryTreeNode<T>[] = [];
560
- let node: BinaryTreeNode<T> | null | undefined = beginRoot, last: BinaryTreeNode<T> | null = null;
561
- const depths: Map<BinaryTreeNode<T>, number> = new Map();
562
-
563
- while (stack.length > 0 || node) {
564
- if (node) {
565
- stack.push(node);
566
- node = node.left;
567
- } else {
568
- node = stack[stack.length - 1]
569
- if (!node.right || last === node.right) {
570
- node = stack.pop();
571
- if (node) {
572
- const leftHeight = node.left ? depths.get(node.left) ?? -1 : -1;
573
- const rightHeight = node.right ? depths.get(node.right) ?? -1 : -1;
574
- depths.set(node, 1 + Math.max(leftHeight, rightHeight));
575
- last = node;
576
- node = null;
577
- }
578
- } else node = node.right
579
- }
580
- }
581
-
582
- return depths.get(beginRoot) ?? -1;
583
- }
584
- }
585
-
586
- /**
587
- * The `getMinHeight` function calculates the minimum height of a binary tree using either a recursive or iterative
588
- * approach.
589
- * @param {BinaryTreeNode<T> | null} [beginRoot] - The `beginRoot` parameter is an optional parameter of type
590
- * `BinaryTreeNode<T> | null`. It represents the starting node from which to calculate the minimum height of the binary
591
- * tree. If no value is provided for `beginRoot`, the function will use the root node of the binary tree.
592
- * @returns The function `getMinHeight` returns the minimum height of the binary tree.
593
- */
594
- getMinHeight(beginRoot?: BinaryTreeNode<T> | null): number {
595
- beginRoot = beginRoot || this.root;
596
- if (!beginRoot) return -1;
597
-
598
- if (this._loopType === LoopType.recursive) {
599
- const _getMinHeight = (cur: BinaryTreeNode<T> | null | undefined): number => {
600
- if (!cur) return 0;
601
- if (!cur.left && !cur.right) return 0;
602
- const leftMinHeight = _getMinHeight(cur.left);
603
- const rightMinHeight = _getMinHeight(cur.right);
604
- return Math.min(leftMinHeight, rightMinHeight) + 1;
605
- };
606
-
607
- return _getMinHeight(beginRoot);
608
- } else {
609
- const stack: BinaryTreeNode<T>[] = [];
610
- let node: BinaryTreeNode<T> | null | undefined = beginRoot, last: BinaryTreeNode<T> | null = null;
611
- const depths: Map<BinaryTreeNode<T>, number> = new Map();
612
-
613
- while (stack.length > 0 || node) {
614
- if (node) {
615
- stack.push(node);
616
- node = node.left;
617
- } else {
618
- node = stack[stack.length - 1]
619
- if (!node.right || last === node.right) {
620
- node = stack.pop();
621
- if (node) {
622
- const leftMinHeight = node.left ? depths.get(node.left) ?? -1 : -1;
623
- const rightMinHeight = node.right ? depths.get(node.right) ?? -1 : -1;
624
- depths.set(node, 1 + Math.min(leftMinHeight, rightMinHeight));
625
- last = node;
626
- node = null;
627
- }
628
- } else node = node.right
629
- }
630
- }
631
-
632
- return depths.get(beginRoot) ?? -1;
633
- }
634
- }
635
-
636
- /**
637
- * The function checks if a binary tree is balanced by comparing the minimum height and the maximum height of the tree.
638
- * @param {BinaryTreeNode<T> | null} [beginRoot] - The `beginRoot` parameter is the root node of a binary tree. It is
639
- * of type `BinaryTreeNode<T> | null`, which means it can either be a `BinaryTreeNode` object or `null`.
640
- * @returns The method is returning a boolean value.
641
- */
642
- isBalanced(beginRoot?: BinaryTreeNode<T> | null): boolean {
643
- return (this.getMinHeight(beginRoot) + 1 >= this.getHeight(beginRoot));
644
- }
645
-
646
- /**
647
- * The function `getNodes` returns an array of binary tree nodes that match a given property value, with options for
648
- * searching recursively or iteratively.
649
- * @param {BinaryTreeNodeId | T} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
650
- * generic type `T`. It represents the property of the binary tree node that you want to search for.
651
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
652
- * specifies the property name to use when searching for nodes. If not provided, it defaults to 'id'.
653
- * @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
654
- * return only one node that matches the `nodeProperty` or `propertyName` criteria. If `onlyOne` is set to `true`, the
655
- * function will stop traversing the tree and return the first matching node. If `
656
- * @returns The function `getNodes` returns an array of `BinaryTreeNode<T> | null | undefined` objects.
657
- */
658
- getNodes(nodeProperty: BinaryTreeNodeId | T, propertyName ?: BinaryTreeNodePropertyName, onlyOne ?: boolean) {
659
- if (!this.root) return [] as null[];
660
- propertyName = propertyName ?? 'id';
661
-
662
- const result: (BinaryTreeNode<T> | null | undefined)[] = [];
663
-
664
- if (this._loopType === LoopType.recursive) {
665
- const _traverse = (cur: BinaryTreeNode<T>) => {
666
- if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return;
667
- if (!cur.left && !cur.right) return;
668
- cur.left && _traverse(cur.left);
669
- cur.right && _traverse(cur.right);
670
- }
671
-
672
- _traverse(this.root);
673
- } else {
674
- const queue: BinaryTreeNode<T>[] = [this.root];
675
- while (queue.length > 0) {
676
- const cur = queue.shift();
677
- if (cur) {
678
- if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return result;
679
- cur.left && queue.push(cur.left);
680
- cur.right && queue.push(cur.right);
681
- }
682
- }
683
- }
684
-
685
- return result;
686
- }
687
-
688
- /**
689
- * The function checks if a binary tree node has a specific property or if any node in the tree has a specific
690
- * property.
691
- * @param {BinaryTreeNodeId | T} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
692
- * generic type `T`. It represents the property of a binary tree node that you want to check.
693
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
694
- * specifies the name of the property to check for in the nodes.
695
- * @returns a boolean value.
696
- */
697
- has(nodeProperty: BinaryTreeNodeId | T, propertyName ?: BinaryTreeNodePropertyName): boolean {
698
- return this.getNodes(nodeProperty, propertyName).length > 0;
699
- }
700
-
701
- /**
702
- * The function returns the first binary tree node that matches the given property name and value, or null if no match
703
- * is found.
704
- * @param {BinaryTreeNodeId | T} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
705
- * generic type `T`. It represents the property of the binary tree node that you want to search for.
706
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
707
- * specifies the property of the binary tree node to search for. If not provided, it defaults to `'id'`.
708
- * @returns a BinaryTreeNode object or null.
709
- */
710
- get(nodeProperty: BinaryTreeNodeId | T, propertyName ?: BinaryTreeNodePropertyName): BinaryTreeNode<T> | null {
711
- propertyName = propertyName ?? 'id';
712
- return this.getNodes(nodeProperty, propertyName, true)[0] ?? null;
713
- }
714
-
715
- /**
716
- * The function getPathToRoot returns an array of BinaryTreeNode objects representing the path from a given node to the
717
- * root of a binary tree.
718
- * @param node - The `node` parameter is a BinaryTreeNode object.
719
- * @returns The function `getPathToRoot` returns an array of `BinaryTreeNode<T>` objects, representing the path from
720
- * the given `node` to the root of the binary tree.
721
- */
722
- getPathToRoot(node: BinaryTreeNode<T>): BinaryTreeNode<T>[] {
723
- const result: BinaryTreeNode<T>[] = [];
724
- while (node.parent) {
725
- result.unshift(node);
726
- node = node.parent;
727
- }
728
- result.unshift(node);
729
- return result;
730
- }
731
-
732
- getLeftMost(): BinaryTreeNode<T> | null;
733
-
734
- getLeftMost(node: BinaryTreeNode<T>): BinaryTreeNode<T>;
735
-
736
- /**
737
- * The `getLeftMost` function returns the leftmost node in a binary tree, either recursively or iteratively using tail
738
- * recursion optimization.
739
- * @param {BinaryTreeNode<T> | null} [node] - The `node` parameter is an optional parameter of type `BinaryTreeNode<T>
740
- * | null`. It represents the starting node from which to find the leftmost node in a binary tree. If no node is
741
- * provided, the function will use the root node of the binary tree.
742
- * @returns The `getLeftMost` function returns the leftmost node in a binary tree.
743
- */
744
- getLeftMost(node?: BinaryTreeNode<T> | null): BinaryTreeNode<T> | null {
745
- node = node ?? this.root;
746
- if (!node) return node;
747
-
748
- if (this._loopType === LoopType.recursive) {
749
-
750
- const _traverse = (cur: BinaryTreeNode<T>): BinaryTreeNode<T> => {
751
- if (!cur.left) return cur;
752
- return _traverse(cur.left);
753
- }
754
-
755
- return _traverse(node);
756
- } else {
757
- // Indirect implementation of iteration using tail recursion optimization
758
- const _traverse = trampoline((cur: BinaryTreeNode<T>) => {
759
- if (!cur.left) return cur;
760
- return _traverse.cont(cur.left);
761
- });
762
-
763
- return _traverse(node);
764
- }
765
- }
766
-
767
- getRightMost(): BinaryTreeNode<T> | null;
768
-
769
- getRightMost(node: BinaryTreeNode<T>): BinaryTreeNode<T>;
770
-
771
- /**
772
- * The `getRightMost` function returns the rightmost node in a binary tree, either recursively or iteratively using
773
- * tail recursion optimization.
774
- * @param {BinaryTreeNode<T> | null} [node] - The `node` parameter is an optional parameter of type `BinaryTreeNode<T>
775
- * | null`. It represents the starting node from which to find the rightmost node in a binary tree. If no node is
776
- * provided, the function will use the root node of the binary tree.
777
- * @returns The `getRightMost` function returns the rightmost node in a binary tree.
778
- */
779
- getRightMost(node?: BinaryTreeNode<T> | null): BinaryTreeNode<T> | null {
780
- node = node ?? this.root;
781
- if (!node) return node;
782
-
783
- if (this._loopType === LoopType.recursive) {
784
- const _traverse = (cur: BinaryTreeNode<T>): BinaryTreeNode<T> => {
785
- if (!cur.right) return cur;
786
- return _traverse(cur.right);
787
- }
788
-
789
- return _traverse(node);
790
- } else {
791
- // Indirect implementation of iteration using tail recursion optimization
792
- const _traverse = trampoline((cur: BinaryTreeNode<T>) => {
793
- if (!cur.right) return cur;
794
- return _traverse.cont(cur.right);
795
- });
796
-
797
- return _traverse(node);
798
- }
799
- }
800
-
801
- // --- start additional methods ---
802
-
803
- /**
804
- * The `isBST` function checks if a binary tree is a binary search tree.
805
- * @param {BinaryTreeNode<T> | null} [node] - The `node` parameter is an optional parameter of type `BinaryTreeNode<T>
806
- * | null`. It represents the root node of the binary search tree (BST) that we want to check for validity. If no node
807
- * is provided, the function will default to using the root node of the BST instance that
808
- * @returns The `isBST` function returns a boolean value. It returns `true` if the binary tree is a valid binary search
809
- * tree, and `false` otherwise.
810
- */
811
- isBST(node?: BinaryTreeNode<T> | null): boolean {
812
- node = node ?? this.root;
813
- if (!node) return true;
814
-
815
- if (this._loopType === LoopType.recursive) {
816
- const dfs = (cur: BinaryTreeNode<T> | null | undefined, min: BinaryTreeNodeId, max: BinaryTreeNodeId): boolean => {
817
- if (!cur) return true;
818
- if (cur.id <= min || cur.id >= max) return false;
819
- return dfs(cur.left, min, cur.id) && dfs(cur.right, cur.id, max);
820
- }
821
-
822
- return dfs(node, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
823
- } else {
824
- const stack = [];
825
- let prev = Number.MIN_SAFE_INTEGER, curr: BinaryTreeNode<T> | null | undefined = node;
826
- while (curr || stack.length > 0) {
827
- while (curr) {
828
- stack.push(curr);
829
- curr = curr.left;
830
- }
831
- curr = stack.pop()!;
832
- if (!(curr) || prev >= curr.id) return false;
833
- prev = curr.id;
834
- curr = curr.right;
835
- }
836
- return true;
837
- }
838
- }
839
-
840
- /**
841
- * The function calculates the size and count of a subtree in a binary tree using either recursive or iterative
842
- * traversal.
843
- * @param {BinaryTreeNode<T> | null | undefined} subTreeRoot - The `subTreeRoot` parameter is the root node of a binary
844
- * tree.
845
- * @returns The function `getSubTreeSizeAndCount` returns an array `[number, number]`. The first element of the array
846
- * represents the size of the subtree, and the second element represents the count of the nodes in the subtree.
847
- */
848
- getSubTreeSizeAndCount(subTreeRoot: BinaryTreeNode<T> | null | undefined) {
849
- const res: [number, number] = [0, 0];
850
- if (!subTreeRoot) return res;
851
-
852
- if (this._loopType === LoopType.recursive) {
853
- const _traverse = (cur: BinaryTreeNode<T>) => {
854
- res[0]++;
855
- res[1] += cur.count;
856
- cur.left && _traverse(cur.left);
857
- cur.right && _traverse(cur.right);
858
- }
859
-
860
- _traverse(subTreeRoot);
861
- return res;
862
- } else {
863
- const stack: BinaryTreeNode<T>[] = [subTreeRoot];
864
-
865
- while (stack.length > 0) {
866
- const cur = stack.pop()!;
867
- res[0]++;
868
- res[1] += cur.count;
869
- cur.right && stack.push(cur.right);
870
- cur.left && stack.push(cur.left);
871
- }
872
-
873
- return res;
874
- }
875
- }
876
-
877
- /**
878
- * The function `subTreeSum` calculates the sum of a specified property in a binary tree, either recursively or
879
- * iteratively.
880
- * @param subTreeRoot - The subTreeRoot parameter is the root node of the subtree for which you want to calculate the
881
- * sum.
882
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
883
- * specifies the property of the `BinaryTreeNode` object to use for calculating the sum. If `propertyName` is not
884
- * provided, it defaults to `'val'`.
885
- * @returns a number, which is the sum of the values of the nodes in the subtree rooted at `subTreeRoot`.
886
- */
887
- subTreeSum(subTreeRoot: BinaryTreeNode<T>, propertyName ?: BinaryTreeNodePropertyName): number {
888
- propertyName = propertyName ?? 'val';
889
- if (!subTreeRoot) return 0;
890
-
891
- let sum = 0;
892
-
893
- const _sumByProperty = (cur: BinaryTreeNode<T>) => {
894
- let needSum: number;
895
- switch (propertyName) {
896
- case 'id':
897
- needSum = cur.id;
898
- break;
899
- case 'count':
900
- needSum = cur.count;
901
- break;
902
- case 'val':
903
- needSum = typeof cur.val === 'number' ? cur.val : 0;
904
- break;
905
- default:
906
- needSum = cur.id;
907
- break;
908
- }
909
- return needSum;
910
- }
911
-
912
- if (this._loopType === LoopType.recursive) {
913
- const _traverse = (cur: BinaryTreeNode<T>): void => {
914
- sum += _sumByProperty(cur);
915
- cur.left && _traverse(cur.left);
916
- cur.right && _traverse(cur.right);
917
- }
918
-
919
- _traverse(subTreeRoot);
920
- } else {
921
- const stack: BinaryTreeNode<T>[] = [subTreeRoot];
922
-
923
- while (stack.length > 0) {
924
- const cur = stack.pop()!;
925
- sum += _sumByProperty(cur);
926
- cur.right && stack.push(cur.right);
927
- cur.left && stack.push(cur.left);
928
- }
929
- }
930
-
931
- return sum;
932
- }
933
-
934
- /**
935
- * The function `subTreeAdd` adds a specified delta value to a property of each node in a binary tree.
936
- * @param subTreeRoot - The `subTreeRoot` parameter is the root node of the subtree where the values will be modified.
937
- * @param {number} delta - The `delta` parameter is a number that represents the amount by which the property value of
938
- * each node in the subtree should be increased or decreased.
939
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
940
- * specifies the property of the `BinaryTreeNode` that should be modified. It defaults to `'id'` if not provided.
941
- * @returns a boolean value, which is `true`.
942
- */
943
- subTreeAdd(subTreeRoot: BinaryTreeNode<T>, delta: number, propertyName ?: BinaryTreeNodePropertyName): boolean {
944
- propertyName = propertyName ?? 'id';
945
- if (!subTreeRoot) return false;
946
-
947
- const _addByProperty = (cur: BinaryTreeNode<T>) => {
948
- switch (propertyName) {
949
- case 'id':
950
- cur.id += delta;
951
- break;
952
- case 'count':
953
- cur.count += delta;
954
- this.count += delta;
955
- break;
956
- default:
957
- cur.id += delta;
958
- break;
959
- }
960
- }
961
-
962
- if (this._loopType === LoopType.recursive) {
963
- const _traverse = (cur: BinaryTreeNode<T>) => {
964
- _addByProperty(cur);
965
- cur.left && _traverse(cur.left);
966
- cur.right && _traverse(cur.right);
967
- };
968
-
969
- _traverse(subTreeRoot);
970
- } else {
971
- const stack: BinaryTreeNode<T>[] = [subTreeRoot];
972
-
973
- while (stack.length > 0) {
974
- const cur = stack.pop()!;
975
-
976
- _addByProperty(cur);
977
- cur.right && stack.push(cur.right);
978
- cur.left && stack.push(cur.left);
979
- }
980
- }
981
- return true;
982
- }
983
-
984
- BFS(): BinaryTreeNodeId[];
985
-
986
- BFS(nodeOrPropertyName: 'id'): BinaryTreeNodeId[];
987
-
988
- BFS(nodeOrPropertyName: 'val'): T[];
989
-
990
- BFS(nodeOrPropertyName: 'node'): BinaryTreeNode<T>[];
991
-
992
- BFS(nodeOrPropertyName: 'count'): number[];
993
-
994
- /**
995
- * The BFS function performs a breadth-first search on a binary tree and returns the results based on a specified node
996
- * or property name.
997
- * @param {NodeOrPropertyName} [nodeOrPropertyName] - The parameter `nodeOrPropertyName` is an optional parameter that
998
- * represents either a node or a property name. If a node is provided, the breadth-first search algorithm will be
999
- * performed starting from that node. If a property name is provided, the breadth-first search algorithm will be
1000
- * performed starting from the root node
1001
- * @returns an object of type `ResultsByProperty<T>`.
1002
- */
1003
- BFS(nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<T> {
1004
- nodeOrPropertyName = nodeOrPropertyName ?? 'id';
1005
- this._resetResults();
1006
- const queue: Array<BinaryTreeNode<T> | null | undefined> = [this.root];
1007
-
1008
- while (queue.length !== 0) {
1009
- const cur = queue.shift();
1010
- if (cur) {
1011
- this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1012
- if (cur?.left !== null) queue.push(cur.left);
1013
- if (cur?.right !== null) queue.push(cur.right);
1014
- }
1015
- }
1016
-
1017
- return this._getResultByPropertyName(nodeOrPropertyName);
1018
- }
1019
-
1020
- DFS(): BinaryTreeNodeId[];
1021
-
1022
- DFS(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[];
1023
-
1024
- DFS(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'val'): T[];
1025
-
1026
- DFS(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'node'): BinaryTreeNode<T>[];
1027
-
1028
- DFS(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'count'): number[];
1029
-
1030
- /**
1031
- * The DFS function performs a depth-first search traversal on a binary tree and returns the results based on the
1032
- * specified pattern and node or property name.
1033
- * @param {'in' | 'pre' | 'post'} [pattern] - The "pattern" parameter is used to specify the order in which the nodes
1034
- * of a binary tree are traversed during the Depth-First Search (DFS) algorithm. It can take one of three values: 'in',
1035
- * 'pre', or 'post'.
1036
- * @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is a string that represents
1037
- * either the name of a property in the `BinaryTreeNode` object or the value of the `id` property in the
1038
- * `BinaryTreeNode` object. This parameter is used to accumulate the results based on the specified property name. If
1039
- * no value
1040
- * @returns an object of type `ResultsByProperty<T>`.
1041
- */
1042
- DFS(pattern ?: 'in' | 'pre' | 'post', nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<T> {
1043
- pattern = pattern ?? 'in';
1044
- nodeOrPropertyName = nodeOrPropertyName ?? 'id';
1045
- this._resetResults();
1046
- const _traverse = (node: BinaryTreeNode<T>) => {
1047
- switch (pattern) {
1048
- case 'in':
1049
- if (node.left) _traverse(node.left);
1050
- this._accumulatedByPropertyName(node, nodeOrPropertyName);
1051
- if (node.right) _traverse(node.right);
1052
- break;
1053
- case 'pre':
1054
- this._accumulatedByPropertyName(node, nodeOrPropertyName);
1055
- if (node.left) _traverse(node.left);
1056
- if (node.right) _traverse(node.right);
1057
- break;
1058
- case 'post':
1059
- if (node.left) _traverse(node.left);
1060
- if (node.right) _traverse(node.right);
1061
- this._accumulatedByPropertyName(node, nodeOrPropertyName);
1062
- break;
1063
- }
1064
- };
1065
-
1066
- this.root && _traverse(this.root);
1067
- return this._getResultByPropertyName(nodeOrPropertyName);
1068
- }
1069
-
1070
- DFSIterative(): BinaryTreeNodeId[];
1071
-
1072
- DFSIterative(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[];
1073
-
1074
- DFSIterative(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'val'): T[];
1075
-
1076
- DFSIterative(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'node'): BinaryTreeNode<T>[];
1077
-
1078
- DFSIterative(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'count'): number[];
1079
-
1080
- /**
1081
- * Time complexity is O(n)
1082
- * Space complexity of Iterative DFS equals to recursive DFS which is O(n) because of the stack
1083
- * @param pattern
1084
- * @param nodeOrPropertyName
1085
- * @constructor
1086
- */
1087
- DFSIterative(pattern ?: 'in' | 'pre' | 'post', nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<T> {
1088
- pattern = pattern || 'in';
1089
- nodeOrPropertyName = nodeOrPropertyName || 'id';
1090
- this._resetResults();
1091
- if (!this.root) return this._getResultByPropertyName(nodeOrPropertyName);
1092
- // 0: visit, 1: print
1093
- const stack: { opt: 0 | 1, node: BinaryTreeNode<T> | null | undefined }[] = [{opt: 0, node: this.root}];
1094
-
1095
- while (stack.length > 0) {
1096
- const cur = stack.pop();
1097
- if (!cur || !cur.node) continue;
1098
- if (cur.opt === 1) {
1099
- this._accumulatedByPropertyName(cur.node, nodeOrPropertyName);
1100
- } else {
1101
- switch (pattern) {
1102
- case 'in':
1103
- stack.push({opt: 0, node: cur.node.right});
1104
- stack.push({opt: 1, node: cur.node});
1105
- stack.push({opt: 0, node: cur.node.left});
1106
- break;
1107
- case 'pre':
1108
- stack.push({opt: 0, node: cur.node.right});
1109
- stack.push({opt: 0, node: cur.node.left});
1110
- stack.push({opt: 1, node: cur.node});
1111
- break;
1112
- case 'post':
1113
- stack.push({opt: 1, node: cur.node});
1114
- stack.push({opt: 0, node: cur.node.right});
1115
- stack.push({opt: 0, node: cur.node.left});
1116
- break;
1117
- default:
1118
- stack.push({opt: 0, node: cur.node.right});
1119
- stack.push({opt: 1, node: cur.node});
1120
- stack.push({opt: 0, node: cur.node.left});
1121
- break;
1122
- }
1123
- }
1124
- }
1125
-
1126
- return this._getResultByPropertyName(nodeOrPropertyName);
1127
- }
1128
-
1129
- levelIterative(node: BinaryTreeNode<T> | null): BinaryTreeNodeId[];
1130
-
1131
- levelIterative(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[];
1132
-
1133
- levelIterative(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: 'val'): T[];
1134
-
1135
- levelIterative(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: 'node'): BinaryTreeNode<T>[];
1136
-
1137
- levelIterative(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: 'count'): number[];
1138
-
1139
- /**
1140
- * The `levelIterative` function performs a level-order traversal on a binary tree and returns the values of the nodes
1141
- * in an array, based on a specified property name.
1142
- * @param {BinaryTreeNode<T> | null} node - The `node` parameter is a BinaryTreeNode object representing the starting
1143
- * node for the level order traversal. It can be null if no specific node is provided, in which case the root node of
1144
- * the tree is used as the starting node.
1145
- * @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is an optional parameter that
1146
- * can be either a `BinaryTreeNode` property name or the string `'id'`. If a property name is provided, the function
1147
- * will accumulate results based on that property. If no property name is provided, the function will default to
1148
- * accumulating results
1149
- * @returns The function `levelIterative` returns an object of type `ResultsByProperty<T>`.
1150
- */
1151
- levelIterative(node: BinaryTreeNode<T> | null, nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<T> {
1152
- nodeOrPropertyName = nodeOrPropertyName || 'id';
1153
- node = node || this.root;
1154
- if (!node) return [];
1155
-
1156
- this._resetResults();
1157
- const queue: BinaryTreeNode<T>[] = [node];
1158
-
1159
- while (queue.length > 0) {
1160
- const cur = queue.shift();
1161
- if (cur) {
1162
- this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1163
- if (cur.left) {
1164
- queue.push(cur.left);
1165
- }
1166
- if (cur.right) {
1167
- queue.push(cur.right);
1168
- }
1169
- }
1170
- }
1171
-
1172
- return this._getResultByPropertyName(nodeOrPropertyName);
1173
- }
1174
-
1175
- listLevels(node: BinaryTreeNode<T> | null): BinaryTreeNodeId[][];
1176
-
1177
- listLevels(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[][];
1178
-
1179
- listLevels(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: 'val'): T[][];
1180
-
1181
- listLevels(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: 'node'): BinaryTreeNode<T>[][];
1182
-
1183
- listLevels(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: 'count'): number[][];
1184
-
1185
- /**
1186
- * The `listLevels` function collects nodes from a binary tree by a specified property and organizes them into levels.
1187
- * @param {BinaryTreeNode<T> | null} node - The `node` parameter is a BinaryTreeNode object or null. It represents the
1188
- * root node of a binary tree. If it is null, the function will use the root node of the current binary tree instance.
1189
- * @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is an optional parameter that
1190
- * specifies the property of the `BinaryTreeNode` object to collect at each level. It can be one of the following
1191
- * values:
1192
- * @returns The function `listLevels` returns a 2D array of `ResultByProperty<T>` objects.
1193
- */
1194
- listLevels(node: BinaryTreeNode<T> | null, nodeOrPropertyName?: NodeOrPropertyName): ResultByProperty<T>[][] {
1195
- nodeOrPropertyName = nodeOrPropertyName || 'id';
1196
- node = node || this.root;
1197
- if (!node) return [];
1198
-
1199
- const levelsNodes: ResultByProperty<T>[][] = [];
1200
-
1201
- const collectByProperty = (node: BinaryTreeNode<T>, level: number) => {
1202
- switch (nodeOrPropertyName) {
1203
- case 'id':
1204
- levelsNodes[level].push(node.id);
1205
- break;
1206
- case 'val':
1207
- levelsNodes[level].push(node.val);
1208
- break;
1209
- case 'node':
1210
- levelsNodes[level].push(node);
1211
- break;
1212
- case 'count':
1213
- levelsNodes[level].push(node.count);
1214
- break;
1215
- default:
1216
- levelsNodes[level].push(node.id);
1217
- break;
1218
- }
1219
- }
1220
-
1221
- if (this._loopType === LoopType.recursive) {
1222
- const _recursive = (node: BinaryTreeNode<T>, level: number) => {
1223
- if (!levelsNodes[level]) levelsNodes[level] = [];
1224
- collectByProperty(node, level);
1225
- if (node.left) _recursive(node.left, level + 1);
1226
- if (node.right) _recursive(node.right, level + 1);
1227
- };
1228
-
1229
- _recursive(node, 0);
1230
- } else {
1231
- const stack: [BinaryTreeNode<T>, number][] = [[node, 0]];
1232
-
1233
- while (stack.length > 0) {
1234
- const head = stack.pop()!;
1235
- const [node, level] = head;
1236
-
1237
- if (!levelsNodes[level]) levelsNodes[level] = [];
1238
- collectByProperty(node, level);
1239
- if (node.right) stack.push([node.right, level + 1]);
1240
- if (node.left) stack.push([node.left, level + 1]);
1241
- }
1242
- }
1243
-
1244
- return levelsNodes;
1245
- }
1246
-
1247
- /**
1248
- * The function returns the predecessor of a given node in a binary tree.
1249
- * @param node - The parameter `node` is a BinaryTreeNode object, representing a node in a binary tree.
1250
- * @returns the predecessor of the given node in a binary tree.
1251
- */
1252
- getPredecessor(node: BinaryTreeNode<T>): BinaryTreeNode<T> {
1253
- if (node.left) {
1254
- let predecessor: BinaryTreeNode<T> | null | undefined = node.left;
1255
- while (!(predecessor) || predecessor.right && predecessor.right !== node) {
1256
- if (predecessor) {
1257
- predecessor = predecessor.right;
1258
- }
1259
- }
1260
- return predecessor;
1261
- } else {
1262
- return node;
1263
- }
1264
- }
1265
-
1266
- morris(): BinaryTreeNodeId[];
1267
-
1268
- morris(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[];
1269
-
1270
- morris(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'val'): T[];
1271
-
1272
- morris(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'node'): BinaryTreeNode<T>[];
1273
-
1274
- morris(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'count'): number[];
1275
-
1276
- /**
1277
- * The `morris` function performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris
1278
- * traversal algorithm and returns the results based on the specified property name.
1279
- * The time complexity of Morris traversal is O(n), it's may slower than others
1280
- * The space complexity Morris traversal is O(1) because no using stack
1281
- * @param {'in' | 'pre' | 'post'} [pattern] - The `pattern` parameter is an optional parameter that determines the
1282
- * traversal pattern of the binary tree. It can have one of three values:
1283
- * @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is used to specify the
1284
- * property of the nodes that you want to retrieve in the results. It can be either the node itself or the name of the
1285
- * property. If not provided, it defaults to `'id'`.
1286
- * @returns The function `morris` returns an object of type `ResultsByProperty<T>`.
1287
- */
1288
- morris(pattern?: 'in' | 'pre' | 'post', nodeOrPropertyName?: NodeOrPropertyName): ResultsByProperty<T> {
1289
- if (this.root === null) return [];
1290
-
1291
- pattern = pattern || 'in';
1292
- nodeOrPropertyName = nodeOrPropertyName || 'id';
1293
-
1294
- this._resetResults();
1295
-
1296
- let cur: BinaryTreeNode<T> | null | undefined = this.root;
1297
- const _reverseEdge = (node: BinaryTreeNode<T> | null | undefined) => {
1298
- let pre: BinaryTreeNode<T> | null | undefined = null;
1299
- let next: BinaryTreeNode<T> | null | undefined = null;
1300
- while (node) {
1301
- next = node.right;
1302
- node.right = pre;
1303
- pre = node;
1304
- node = next;
1305
- }
1306
- return pre;
1307
- };
1308
- const _printEdge = (node: BinaryTreeNode<T> | null) => {
1309
- const tail: BinaryTreeNode<T> | null | undefined = _reverseEdge(node);
1310
- let cur: BinaryTreeNode<T> | null | undefined = tail;
1311
- while (cur) {
1312
- this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1313
- cur = cur.right;
1314
- }
1315
- _reverseEdge(tail);
1316
- };
1317
- switch (pattern) {
1318
- case 'in':
1319
- while (cur) {
1320
- if (cur.left) {
1321
- const predecessor = this.getPredecessor(cur);
1322
- if (!predecessor.right) {
1323
- predecessor.right = cur;
1324
- cur = cur.left;
1325
- continue;
1326
- } else {
1327
- predecessor.right = null;
1328
- }
1329
- }
1330
- this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1331
- cur = cur.right;
1332
- }
1333
- break;
1334
- case 'pre':
1335
- while (cur) {
1336
- if (cur.left) {
1337
- const predecessor = this.getPredecessor(cur);
1338
- if (!predecessor.right) {
1339
- predecessor.right = cur;
1340
- this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1341
- cur = cur.left;
1342
- continue;
1343
- } else {
1344
- predecessor.right = null;
1345
- }
1346
- } else {
1347
- this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1348
- }
1349
- cur = cur.right;
1350
- }
1351
- break;
1352
- case 'post':
1353
- while (cur) {
1354
- if (cur.left) {
1355
- const predecessor = this.getPredecessor(cur);
1356
- if (predecessor.right === null) {
1357
- predecessor.right = cur;
1358
- cur = cur.left;
1359
- continue;
1360
- } else {
1361
- predecessor.right = null;
1362
- _printEdge(cur.left);
1363
- }
1364
- }
1365
- cur = cur.right;
1366
- }
1367
- _printEdge(this.root);
1368
- break;
1369
- }
1370
-
1371
- return this._getResultByPropertyName(nodeOrPropertyName);
1372
- }
1373
-
1374
- /**
1375
- * The function resets the values of several arrays used for tracking visited nodes and their properties.
1376
- */
1377
- protected _resetResults() {
1378
- this._visitedId = [];
1379
- this._visitedVal = [];
1380
- this._visitedNode = [];
1381
- this._visitedCount = [];
1382
- this._visitedLeftSum = [];
1383
- }
1384
-
1385
- /**
1386
- * The function checks if a given property of a binary tree node matches a specified value, and if so, adds the node to
1387
- * a result array.
1388
- * @param cur - The current binary tree node that is being checked.
1389
- * @param {(BinaryTreeNode<T> | null | undefined)[]} result - An array that stores the matching nodes found during the
1390
- * traversal.
1391
- * @param {BinaryTreeNodeId | T} nodeProperty - The `nodeProperty` parameter is the value that we are searching for in
1392
- * the binary tree nodes. It can be either the `id`, `count`, or `val` property of the node.
1393
- * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
1394
- * specifies the property of the `BinaryTreeNode` object that you want to compare with the `nodeProperty` value. It can
1395
- * be one of the following values: 'id', 'count', or 'val'. If no `propertyName` is provided,
1396
- * @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
1397
- * stop after finding the first matching node or continue searching for all matching nodes. If `onlyOne` is set to
1398
- * `true`, the function will stop after finding the first matching node and return `true`. If `onlyOne
1399
- * @returns a boolean value indicating whether or not a node was pushed into the result array.
1400
- */
1401
- protected _pushByPropertyNameStopOrNot(cur: BinaryTreeNode<T>, result: (BinaryTreeNode<T> | null | undefined)[], nodeProperty: BinaryTreeNodeId | T, propertyName ?: BinaryTreeNodePropertyName, onlyOne ?: boolean) {
1402
- switch (propertyName) {
1403
- case 'id':
1404
- if (cur.id === nodeProperty) {
1405
- result.push(cur);
1406
- return !!onlyOne;
1407
- }
1408
- break;
1409
- case 'count':
1410
- if (cur.count === nodeProperty) {
1411
- result.push(cur);
1412
- return !!onlyOne;
1413
- }
1414
- break;
1415
- case 'val':
1416
- if (cur.val === nodeProperty) {
1417
- result.push(cur);
1418
- return !!onlyOne;
1419
- }
1420
- break;
1421
- default:
1422
- if (cur.id === nodeProperty) {
1423
- result.push(cur);
1424
- return !!onlyOne;
1425
- }
1426
- break;
1427
- }
1428
- }
1429
-
1430
- /**
1431
- * The function `_accumulatedByPropertyName` pushes a property value of a binary tree node into an array based on the
1432
- * provided property name or a default property name.
1433
- * @param node - The `node` parameter is of type `BinaryTreeNode<T>`, which represents a node in a binary tree.
1434
- * @param {NodeOrPropertyName} [nodeOrPropertyName] - The parameter `nodeOrPropertyName` is an optional parameter that
1435
- * can be either a string representing a property name or a reference to a node object. If it is a string, it specifies
1436
- * the property name of the node that should be accumulated. If it is a node object, it specifies the node itself
1437
- */
1438
- protected _accumulatedByPropertyName(node: BinaryTreeNode<T>, nodeOrPropertyName ?: NodeOrPropertyName) {
1439
- nodeOrPropertyName = nodeOrPropertyName ?? 'id';
1440
-
1441
- switch (nodeOrPropertyName) {
1442
- case 'id':
1443
- this._visitedId.push(node.id);
1444
- break;
1445
- case 'val':
1446
- this._visitedVal.push(node.val);
1447
- break;
1448
- case 'node':
1449
- this._visitedNode.push(node);
1450
- break;
1451
- case 'count':
1452
- this._visitedCount.push(node.count);
1453
- break;
1454
- default:
1455
- this._visitedId.push(node.id);
1456
- break;
1457
- }
1458
- }
1459
-
1460
- /**
1461
- * The function `_getResultByPropertyName` returns different results based on the provided property name or defaulting
1462
- * to 'id'.
1463
- * @param {NodeOrPropertyName} [nodeOrPropertyName] - The parameter `nodeOrPropertyName` is an optional parameter that
1464
- * can accept a value of type `NodeOrPropertyName`.
1465
- * @returns The method returns an object of type `ResultsByProperty<T>`.
1466
- */
1467
- protected _getResultByPropertyName(nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<T> {
1468
- nodeOrPropertyName = nodeOrPropertyName ?? 'id';
1469
-
1470
- switch (nodeOrPropertyName) {
1471
- case 'id':
1472
- return this._visitedId;
1473
- case 'val':
1474
- return this._visitedVal;
1475
- case 'node':
1476
- return this._visitedNode;
1477
- case 'count':
1478
- return this._visitedCount;
1479
- default:
1480
- return this._visitedId;
1481
- }
1482
- }
1483
-
1484
- // --- end additional methods ---
1485
- }