deque-typed 2.0.4 → 2.1.0

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 (101) hide show
  1. package/dist/data-structures/base/iterable-element-base.d.ts +186 -83
  2. package/dist/data-structures/base/iterable-element-base.js +149 -107
  3. package/dist/data-structures/base/iterable-entry-base.d.ts +95 -119
  4. package/dist/data-structures/base/iterable-entry-base.js +59 -116
  5. package/dist/data-structures/base/linear-base.d.ts +250 -192
  6. package/dist/data-structures/base/linear-base.js +137 -274
  7. package/dist/data-structures/binary-tree/avl-tree-counter.d.ts +126 -158
  8. package/dist/data-structures/binary-tree/avl-tree-counter.js +171 -205
  9. package/dist/data-structures/binary-tree/avl-tree-multi-map.d.ts +100 -69
  10. package/dist/data-structures/binary-tree/avl-tree-multi-map.js +135 -87
  11. package/dist/data-structures/binary-tree/avl-tree.d.ts +138 -149
  12. package/dist/data-structures/binary-tree/avl-tree.js +208 -195
  13. package/dist/data-structures/binary-tree/binary-tree.d.ts +476 -632
  14. package/dist/data-structures/binary-tree/binary-tree.js +612 -879
  15. package/dist/data-structures/binary-tree/bst.d.ts +258 -306
  16. package/dist/data-structures/binary-tree/bst.js +505 -481
  17. package/dist/data-structures/binary-tree/red-black-tree.d.ts +107 -179
  18. package/dist/data-structures/binary-tree/red-black-tree.js +114 -209
  19. package/dist/data-structures/binary-tree/tree-counter.d.ts +132 -154
  20. package/dist/data-structures/binary-tree/tree-counter.js +172 -203
  21. package/dist/data-structures/binary-tree/tree-multi-map.d.ts +72 -69
  22. package/dist/data-structures/binary-tree/tree-multi-map.js +105 -85
  23. package/dist/data-structures/graph/abstract-graph.d.ts +238 -233
  24. package/dist/data-structures/graph/abstract-graph.js +267 -237
  25. package/dist/data-structures/graph/directed-graph.d.ts +108 -224
  26. package/dist/data-structures/graph/directed-graph.js +146 -233
  27. package/dist/data-structures/graph/map-graph.d.ts +49 -55
  28. package/dist/data-structures/graph/map-graph.js +56 -59
  29. package/dist/data-structures/graph/undirected-graph.d.ts +103 -146
  30. package/dist/data-structures/graph/undirected-graph.js +129 -149
  31. package/dist/data-structures/hash/hash-map.d.ts +164 -338
  32. package/dist/data-structures/hash/hash-map.js +270 -457
  33. package/dist/data-structures/heap/heap.d.ts +214 -289
  34. package/dist/data-structures/heap/heap.js +340 -349
  35. package/dist/data-structures/heap/max-heap.d.ts +11 -47
  36. package/dist/data-structures/heap/max-heap.js +11 -66
  37. package/dist/data-structures/heap/min-heap.d.ts +12 -47
  38. package/dist/data-structures/heap/min-heap.js +11 -66
  39. package/dist/data-structures/linked-list/doubly-linked-list.d.ts +231 -347
  40. package/dist/data-structures/linked-list/doubly-linked-list.js +368 -494
  41. package/dist/data-structures/linked-list/singly-linked-list.d.ts +261 -310
  42. package/dist/data-structures/linked-list/singly-linked-list.js +447 -466
  43. package/dist/data-structures/linked-list/skip-linked-list.d.ts +0 -107
  44. package/dist/data-structures/linked-list/skip-linked-list.js +0 -100
  45. package/dist/data-structures/priority-queue/max-priority-queue.d.ts +12 -56
  46. package/dist/data-structures/priority-queue/max-priority-queue.js +11 -78
  47. package/dist/data-structures/priority-queue/min-priority-queue.d.ts +11 -57
  48. package/dist/data-structures/priority-queue/min-priority-queue.js +10 -79
  49. package/dist/data-structures/priority-queue/priority-queue.d.ts +2 -61
  50. package/dist/data-structures/priority-queue/priority-queue.js +8 -83
  51. package/dist/data-structures/queue/deque.d.ts +227 -254
  52. package/dist/data-structures/queue/deque.js +309 -348
  53. package/dist/data-structures/queue/queue.d.ts +180 -201
  54. package/dist/data-structures/queue/queue.js +265 -248
  55. package/dist/data-structures/stack/stack.d.ts +124 -102
  56. package/dist/data-structures/stack/stack.js +181 -125
  57. package/dist/data-structures/trie/trie.d.ts +164 -165
  58. package/dist/data-structures/trie/trie.js +189 -172
  59. package/dist/interfaces/binary-tree.d.ts +56 -6
  60. package/dist/interfaces/graph.d.ts +16 -0
  61. package/dist/types/data-structures/base/base.d.ts +1 -1
  62. package/dist/types/data-structures/graph/abstract-graph.d.ts +4 -0
  63. package/dist/types/utils/utils.d.ts +6 -6
  64. package/dist/utils/utils.d.ts +110 -49
  65. package/dist/utils/utils.js +148 -73
  66. package/package.json +2 -2
  67. package/src/data-structures/base/iterable-element-base.ts +238 -115
  68. package/src/data-structures/base/iterable-entry-base.ts +96 -120
  69. package/src/data-structures/base/linear-base.ts +271 -277
  70. package/src/data-structures/binary-tree/avl-tree-counter.ts +198 -216
  71. package/src/data-structures/binary-tree/avl-tree-multi-map.ts +192 -101
  72. package/src/data-structures/binary-tree/avl-tree.ts +239 -206
  73. package/src/data-structures/binary-tree/binary-tree.ts +681 -905
  74. package/src/data-structures/binary-tree/bst.ts +568 -570
  75. package/src/data-structures/binary-tree/red-black-tree.ts +161 -222
  76. package/src/data-structures/binary-tree/tree-counter.ts +199 -218
  77. package/src/data-structures/binary-tree/tree-multi-map.ts +131 -97
  78. package/src/data-structures/graph/abstract-graph.ts +339 -264
  79. package/src/data-structures/graph/directed-graph.ts +146 -236
  80. package/src/data-structures/graph/map-graph.ts +63 -60
  81. package/src/data-structures/graph/undirected-graph.ts +129 -152
  82. package/src/data-structures/hash/hash-map.ts +274 -496
  83. package/src/data-structures/heap/heap.ts +389 -402
  84. package/src/data-structures/heap/max-heap.ts +12 -76
  85. package/src/data-structures/heap/min-heap.ts +13 -76
  86. package/src/data-structures/linked-list/doubly-linked-list.ts +426 -530
  87. package/src/data-structures/linked-list/singly-linked-list.ts +495 -517
  88. package/src/data-structures/linked-list/skip-linked-list.ts +1 -108
  89. package/src/data-structures/priority-queue/max-priority-queue.ts +12 -87
  90. package/src/data-structures/priority-queue/min-priority-queue.ts +11 -88
  91. package/src/data-structures/priority-queue/priority-queue.ts +3 -92
  92. package/src/data-structures/queue/deque.ts +381 -357
  93. package/src/data-structures/queue/queue.ts +310 -264
  94. package/src/data-structures/stack/stack.ts +217 -131
  95. package/src/data-structures/trie/trie.ts +240 -175
  96. package/src/interfaces/binary-tree.ts +240 -6
  97. package/src/interfaces/graph.ts +37 -0
  98. package/src/types/data-structures/base/base.ts +5 -5
  99. package/src/types/data-structures/graph/abstract-graph.ts +5 -0
  100. package/src/types/utils/utils.ts +9 -5
  101. package/src/utils/utils.ts +152 -86
@@ -5,8 +5,10 @@
5
5
  * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
6
6
  * @license MIT License
7
7
  */
8
+
8
9
  import type {
9
10
  BinaryTreeDeleteResult,
11
+ BinaryTreeOptions,
10
12
  BSTNOptKeyOrNode,
11
13
  EntryCallback,
12
14
  IterationType,
@@ -14,23 +16,28 @@ import type {
14
16
  RBTNColor,
15
17
  TreeCounterOptions
16
18
  } from '../../types';
19
+ import { BSTOptions } from '../../types';
20
+ import { BSTNode } from './bst';
17
21
  import { IBinaryTree } from '../../interfaces';
18
22
  import { RedBlackTree, RedBlackTreeNode } from './red-black-tree';
19
23
 
24
+ /**
25
+ * RB-tree node with an extra 'count' field; keeps parent/child links.
26
+ * @remarks Time O(1), Space O(1)
27
+ * @template K
28
+ * @template V
29
+ */
20
30
  export class TreeCounterNode<K = any, V = any> extends RedBlackTreeNode<K, V> {
21
31
  override parent?: TreeCounterNode<K, V> = undefined;
22
32
 
23
33
  /**
24
- * The constructor function initializes a Red-Black Tree node with a key, value, count, and color.
25
- * @param {K} key - The key parameter represents the key of the node in the Red-Black Tree. It is
26
- * used to identify and locate the node within the tree.
27
- * @param {V} [value] - The `value` parameter is an optional parameter that represents the value
28
- * associated with the key in the Red-Black Tree node. It is not required and can be omitted when
29
- * creating a new node.
30
- * @param [count=1] - The `count` parameter represents the number of occurrences of a particular key
31
- * in the Red-Black Tree. It is an optional parameter with a default value of 1.
32
- * @param {RBTNColor} [color=BLACK] - The `color` parameter is used to specify the color of the node
33
- * in a Red-Black Tree. It is optional and has a default value of `'BLACK'`.
34
+ * Create a tree counter node.
35
+ * @remarks Time O(1), Space O(1)
36
+ * @param key - Key of the node.
37
+ * @param [value] - Value associated with the key (ignored in map mode).
38
+ * @param [count] - Initial count for this node (default 1).
39
+ * @param color - Initial color ('RED' or 'BLACK').
40
+ * @returns New TreeCounterNode instance.
34
41
  */
35
42
  constructor(key: K, value?: V, count = 1, color: RBTNColor = 'BLACK') {
36
43
  super(key, value, color);
@@ -39,10 +46,21 @@ export class TreeCounterNode<K = any, V = any> extends RedBlackTreeNode<K, V> {
39
46
 
40
47
  override _left?: TreeCounterNode<K, V> | null | undefined = undefined;
41
48
 
49
+ /**
50
+ * Get the left child pointer.
51
+ * @remarks Time O(1), Space O(1)
52
+ * @returns Left child node, or null/undefined.
53
+ */
42
54
  override get left(): TreeCounterNode<K, V> | null | undefined {
43
55
  return this._left;
44
56
  }
45
57
 
58
+ /**
59
+ * Set the left child and update its parent pointer.
60
+ * @remarks Time O(1), Space O(1)
61
+ * @param v - New left child node, or null/undefined.
62
+ * @returns void
63
+ */
46
64
  override set left(v: TreeCounterNode<K, V> | null | undefined) {
47
65
  if (v) {
48
66
  v.parent = this;
@@ -52,10 +70,21 @@ export class TreeCounterNode<K = any, V = any> extends RedBlackTreeNode<K, V> {
52
70
 
53
71
  override _right?: TreeCounterNode<K, V> | null | undefined = undefined;
54
72
 
73
+ /**
74
+ * Get the right child pointer.
75
+ * @remarks Time O(1), Space O(1)
76
+ * @returns Right child node, or null/undefined.
77
+ */
55
78
  override get right(): TreeCounterNode<K, V> | null | undefined {
56
79
  return this._right;
57
80
  }
58
81
 
82
+ /**
83
+ * Set the right child and update its parent pointer.
84
+ * @remarks Time O(1), Space O(1)
85
+ * @param v - New right child node, or null/undefined.
86
+ * @returns void
87
+ */
59
88
  override set right(v: TreeCounterNode<K, V> | null | undefined) {
60
89
  if (v) {
61
90
  v.parent = this;
@@ -65,20 +94,22 @@ export class TreeCounterNode<K = any, V = any> extends RedBlackTreeNode<K, V> {
65
94
  }
66
95
 
67
96
  /**
68
- *
97
+ * Red-Black Tree–based counter map (key → value with per-node count). Supports O(log N) updates and map-like mode.
98
+ * @remarks Time O(1), Space O(1)
99
+ * @template K
100
+ * @template V
101
+ * @template R
69
102
  */
70
- export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR = object>
71
- extends RedBlackTree<K, V, R, MK, MV, MR>
72
- implements IBinaryTree<K, V, R, MK, MV, MR>
103
+ export class TreeCounter<K = any, V = any, R extends object = object>
104
+ extends RedBlackTree<K, V, R>
105
+ implements IBinaryTree<K, V, R>
73
106
  {
74
107
  /**
75
- * The constructor function initializes a TreeCounter object with optional initial data.
76
- * @param keysNodesEntriesOrRaws - The parameter `keysNodesEntriesOrRaws` is an
77
- * iterable that can contain keys, nodes, entries, or raw elements. It is used to initialize the
78
- * TreeCounter with initial data.
79
- * @param [options] - The `options` parameter is an optional object that can be used to customize the
80
- * behavior of the `TreeCounter` constructor. It can include properties such as `compareKeys` and
81
- * `compareValues`, which are functions used to compare keys and values respectively.
108
+ * Create a TreeCounter and optionally bulk-insert items.
109
+ * @remarks Time O(N log N), Space O(N)
110
+ * @param [keysNodesEntriesOrRaws] - Iterable of keys/nodes/entries/raw items to insert.
111
+ * @param [options] - Options for TreeCounter (comparator, reverse, map mode).
112
+ * @returns New TreeCounter instance.
82
113
  */
83
114
  constructor(
84
115
  keysNodesEntriesOrRaws: Iterable<
@@ -92,71 +123,38 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
92
123
 
93
124
  protected _count = 0;
94
125
 
95
- // TODO the _count is not accurate after nodes count modified
96
126
  /**
97
- * The function calculates the sum of the count property of all nodes in a tree structure.
98
- * @returns the sum of the count property of all nodes in the tree.
127
+ * Get the total aggregate count across all nodes.
128
+ * @remarks Time O(1), Space O(1)
129
+ * @returns Total count.
99
130
  */
131
+
100
132
  get count(): number {
101
133
  return this._count;
102
134
  }
103
135
 
104
136
  /**
105
- * Time Complexity: O(n)
106
- * Space Complexity: O(1)
107
- *
108
- * The function calculates the sum of the count property of all nodes in a tree using depth-first
109
- * search.
110
- * @returns the sum of the count property of all nodes in the tree.
137
+ * Compute the total count by traversing the tree (sums node.count).
138
+ * @remarks Time O(N), Space O(H)
139
+ * @returns Total count recomputed from nodes.
111
140
  */
141
+
112
142
  getComputedCount(): number {
113
143
  let sum = 0;
114
144
  this.dfs(node => (sum += node ? node.count : 0));
115
145
  return sum;
116
146
  }
117
147
 
118
- /**
119
- * The function creates a new TreeCounterNode with the specified key, value, color, and count.
120
- * @param {K} key - The key parameter represents the key of the node being created. It is of type K,
121
- * which is a generic type representing the type of keys in the tree.
122
- * @param {V} [value] - The `value` parameter is an optional parameter that represents the value
123
- * associated with the key in the node. It is of type `V`, which can be any data type.
124
- * @param {RBTNColor} [color=BLACK] - The color parameter is used to specify the color of the node in
125
- * a Red-Black Tree. It can have two possible values: 'RED' or 'BLACK'. The default value is 'BLACK'.
126
- * @param {number} [count] - The `count` parameter represents the number of occurrences of a key in
127
- * the tree. It is an optional parameter and is used to keep track of the number of values associated
128
- * with a key in the tree.
129
- * @returns A new instance of the TreeCounterNode class, casted as TreeCounterNode<K, V>.
130
- */
131
- override createNode(key: K, value?: V, color: RBTNColor = 'BLACK', count?: number): TreeCounterNode<K, V> {
148
+ override _createNode(key: K, value?: V, color: RBTNColor = 'BLACK', count?: number): TreeCounterNode<K, V> {
132
149
  return new TreeCounterNode(key, this._isMapMode ? undefined : value, count, color) as TreeCounterNode<K, V>;
133
150
  }
134
151
 
135
152
  /**
136
- * The function creates a new instance of a TreeCounter with the specified options and returns it.
137
- * @param [options] - The `options` parameter is an optional object that contains additional
138
- * configuration options for creating the `TreeCounter`. It is of type `TreeCounterOptions<K, V,
139
- * R>`.
140
- * @returns a new instance of the `TreeCounter` class, with the provided options merged with the
141
- * existing `iterationType` property. The returned value is casted as `TREE`.
153
+ * Type guard: check whether the input is a TreeCounterNode.
154
+ * @remarks Time O(1), Space O(1)
155
+ * @returns True if the value is a TreeCounterNode.
142
156
  */
143
- override createTree(options?: TreeCounterOptions<K, V, R>) {
144
- return new TreeCounter<K, V, R, MK, MV, MR>([], {
145
- iterationType: this.iterationType,
146
- specifyComparable: this._specifyComparable,
147
- isMapMode: this._isMapMode,
148
- toEntryFn: this._toEntryFn,
149
- ...options
150
- });
151
- }
152
157
 
153
- /**
154
- * The function checks if the input is an instance of the TreeCounterNode class.
155
- * @param {K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined} keyNodeOrEntry - The parameter
156
- * `keyNodeOrEntry` can be of type `R` or `K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined`.
157
- * @returns a boolean value indicating whether the input parameter `keyNodeOrEntry` is
158
- * an instance of the `TreeCounterNode` class.
159
- */
160
158
  override isNode(
161
159
  keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined
162
160
  ): keyNodeOrEntry is TreeCounterNode<K, V> {
@@ -164,20 +162,12 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
164
162
  }
165
163
 
166
164
  /**
167
- * Time Complexity: O(log n)
168
- * Space Complexity: O(1)
169
- *
170
- * The function overrides the add method of a class and adds a new node to a data structure, updating
171
- * the count and returning a boolean indicating success.
172
- * @param {K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined} keyNodeOrEntry - The
173
- * `keyNodeOrEntry` parameter can accept one of the following types:
174
- * @param {V} [value] - The `value` parameter represents the value associated with the key in the
175
- * data structure. It is an optional parameter, so it can be omitted if not needed.
176
- * @param [count=1] - The `count` parameter represents the number of times the key-value pair should
177
- * be added to the data structure. By default, it is set to 1, meaning that if no value is provided
178
- * for `count`, the key-value pair will be added once.
179
- * @returns The method is returning a boolean value. It returns true if the addition of the new node
180
- * was successful, and false otherwise.
165
+ * Insert or increment a node and update aggregate count.
166
+ * @remarks Time O(log N), Space O(1)
167
+ * @param keyNodeOrEntry - Key, node, or [key, value] entry to insert.
168
+ * @param [value] - Value when a bare key is provided (ignored in map mode).
169
+ * @param [count] - How much to increase the node's count (default 1).
170
+ * @returns True if inserted/updated; false if ignored.
181
171
  */
182
172
  override add(
183
173
  keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,
@@ -187,7 +177,6 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
187
177
  const [newNode, newValue] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value, count);
188
178
  const orgCount = newNode?.count || 0;
189
179
  const isSuccessAdded = super.add(newNode, newValue);
190
-
191
180
  if (isSuccessAdded) {
192
181
  this._count += orgCount;
193
182
  return true;
@@ -197,19 +186,11 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
197
186
  }
198
187
 
199
188
  /**
200
- * Time Complexity: O(log n)
201
- * Space Complexity: O(1)
202
- *
203
- * The function `delete` in TypeScript overrides the deletion operation in a binary tree data
204
- * structure, handling cases where nodes have children and maintaining balance in the tree.
205
- * @param {K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined} keyNodeOrEntry - The `predicate`
206
- * parameter in the `delete` method is used to specify the condition or key based on which a node
207
- * should be deleted from the binary tree. It can be a key, a node, or an entry.
208
- * @param [ignoreCount=false] - The `ignoreCount` parameter in the `override delete` method is a
209
- * boolean flag that determines whether to ignore the count of nodes when performing deletion. If
210
- * `ignoreCount` is set to `true`, the method will delete the node regardless of its count. If
211
- * `ignoreCount` is `false
212
- * @returns The `override delete` method returns an array of `BinaryTreeDeleteResult<TreeCounterNode<K, V>>` objects.
189
+ * Delete a node (or decrement its count) and rebalance if needed.
190
+ * @remarks Time O(log N), Space O(1)
191
+ * @param keyNodeOrEntry - Key, node, or [key, value] entry identifying the node.
192
+ * @param [ignoreCount] - If true, remove the node regardless of its count.
193
+ * @returns Array of deletion results including deleted node and a rebalance hint when present.
213
194
  */
214
195
  override delete(
215
196
  keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,
@@ -222,7 +203,6 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
222
203
  let nodeToDelete: OptNode<TreeCounterNode<K, V>>;
223
204
  if (this._isPredicate(keyNodeOrEntry)) nodeToDelete = this.getNode(keyNodeOrEntry);
224
205
  else nodeToDelete = this.isRealNode(keyNodeOrEntry) ? keyNodeOrEntry : this.getNode(keyNodeOrEntry);
225
-
226
206
  if (!nodeToDelete) {
227
207
  return results;
228
208
  }
@@ -259,7 +239,6 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
259
239
  if (successor) {
260
240
  originalColor = successor.color;
261
241
  if (successor.right !== null) replacementNode = successor.right;
262
-
263
242
  if (successor.parent === nodeToDelete) {
264
243
  if (this.isRealNode(replacementNode)) {
265
244
  replacementNode.parent = successor;
@@ -298,8 +277,6 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
298
277
  }
299
278
  }
300
279
  this._size--;
301
-
302
- // If the original color was black, fix the tree
303
280
  if (originalColor === 'BLACK') {
304
281
  this._deleteFixup(replacementNode);
305
282
  }
@@ -310,11 +287,9 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
310
287
  }
311
288
 
312
289
  /**
313
- * Time Complexity: O(1)
314
- * Space Complexity: O(1)
315
- *
316
- * The "clear" function overrides the parent class's "clear" function and also resets the count to
317
- * zero.
290
+ * Remove all nodes and reset aggregate counters.
291
+ * @remarks Time O(N), Space O(1)
292
+ * @returns void
318
293
  */
319
294
  override clear() {
320
295
  super.clear();
@@ -322,111 +297,127 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
322
297
  }
323
298
 
324
299
  /**
325
- * Time Complexity: O(n log n)
326
- * Space Complexity: O(log n)
327
- *
328
- * The `perfectlyBalance` function takes a sorted array of nodes and builds a balanced binary search
329
- * tree using either a recursive or iterative approach.
330
- * @param {IterationType} iterationType - The `iterationType` parameter is an optional parameter that
331
- * specifies the type of iteration to use when building the balanced binary search tree. It has a
332
- * default value of `this.iterationType`, which means it will use the iteration type specified by the
333
- * `iterationType` property of the current object.
334
- * @returns The function `perfectlyBalance` returns a boolean value. It returns `true` if the
335
- * balancing operation is successful, and `false` if there are no nodes to balance.
300
+ * Rebuild the tree into a perfectly balanced form using in-order nodes.
301
+ * @remarks Time O(N), Space O(N)
302
+ * @param [iterationType] - Traversal style to use when constructing the balanced tree.
303
+ * @returns True if rebalancing succeeded (tree not empty).
336
304
  */
337
305
  override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {
338
- const sorted = this.dfs(node => node, 'IN'),
339
- n = sorted.length;
340
- if (sorted.length < 1) return false;
341
-
342
- this.clear();
343
-
344
- if (iterationType === 'RECURSIVE') {
345
- const buildBalanceBST = (l: number, r: number) => {
346
- if (l > r) return;
347
- const m = l + Math.floor((r - l) / 2);
348
- const midNode = sorted[m];
349
- if (this._isMapMode && midNode !== null) this.add(midNode.key, undefined, midNode.count);
350
- else if (midNode !== null) this.add(midNode.key, midNode.value, midNode.count);
351
- buildBalanceBST(l, m - 1);
352
- buildBalanceBST(m + 1, r);
353
- };
354
-
355
- buildBalanceBST(0, n - 1);
356
- return true;
357
- } else {
358
- const stack: [[number, number]] = [[0, n - 1]];
359
- while (stack.length > 0) {
360
- const popped = stack.pop();
361
- if (popped) {
362
- const [l, r] = popped;
363
- if (l <= r) {
364
- const m = l + Math.floor((r - l) / 2);
365
- const midNode = sorted[m];
366
- if (this._isMapMode && midNode !== null) this.add(midNode.key, undefined, midNode.count);
367
- else if (midNode !== null) this.add(midNode.key, midNode.value, midNode.count);
368
- stack.push([m + 1, r]);
369
- stack.push([l, m - 1]);
370
- }
371
- }
372
- }
373
- return true;
374
- }
306
+ const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);
307
+ const n = nodes.length;
308
+ if (n < 1) return false;
309
+
310
+ let total = 0;
311
+ for (const nd of nodes) total += nd ? nd.count : 0;
312
+
313
+ this._clearNodes();
314
+
315
+ const build = (l: number, r: number, parent?: TreeCounterNode<K, V>): TreeCounterNode<K, V> | undefined => {
316
+ if (l > r) return undefined;
317
+ const m = l + ((r - l) >> 1);
318
+ const root = nodes[m]! as TreeCounterNode<K, V>;
319
+ const leftChild = build(l, m - 1, root);
320
+ const rightChild = build(m + 1, r, root);
321
+ root.left = leftChild;
322
+ root.right = rightChild;
323
+ root.parent = parent;
324
+ return root;
325
+ };
326
+
327
+ const newRoot = build(0, n - 1, undefined);
328
+ this._setRoot(newRoot);
329
+ this._size = n;
330
+ this._count = total;
331
+ return true;
375
332
  }
376
333
 
377
334
  /**
378
- * Time complexity: O(n)
379
- * Space complexity: O(n)
380
- *
381
- * The function overrides the clone method to create a deep copy of a tree object.
382
- * @returns The `clone()` method is returning a cloned instance of the `TREE` object.
335
+ * Create a new TreeCounter by mapping each [key, value] entry.
336
+ * @remarks Time O(N log N), Space O(N)
337
+ * @template MK
338
+ * @template MV
339
+ * @template MR
340
+ * @param callback - Function mapping (key, value, index, tree) → [newKey, newValue].
341
+ * @param [options] - Options for the output tree.
342
+ * @param [thisArg] - Value for `this` inside the callback.
343
+ * @returns A new TreeCounter with mapped entries.
383
344
  */
384
- override clone() {
385
- const cloned = this.createTree();
386
- this.bfs(node => cloned.add(node === null ? null : node.key, undefined, node === null ? 0 : node.count));
387
- if (this._isMapMode) cloned._store = this._store;
388
- return cloned;
389
- }
390
-
391
- /**
392
- * The `map` function in TypeScript overrides the default behavior to create a new TreeCounter with
393
- * modified entries based on a provided callback.
394
- * @param callback - The `callback` parameter is a function that will be called for each entry in the
395
- * map. It takes four arguments:
396
- * @param [options] - The `options` parameter in the `override map` function is of type
397
- * `TreeCounterOptions<MK, MV, MR>`. This parameter allows you to provide additional configuration
398
- * options when creating a new `TreeCounter` instance within the `map` function. These options could
399
- * include things like
400
- * @param {any} [thisArg] - The `thisArg` parameter in the `override map` function is used to specify
401
- * the value of `this` when executing the `callback` function. It allows you to set the context
402
- * (value of `this`) for the callback function when it is called within the `map` function. This
403
- * @returns A new TreeCounter instance is being returned, which is populated with entries generated
404
- * by the provided callback function.
405
- */
406
- override map(
345
+ override map<MK = K, MV = V, MR extends object = object>(
407
346
  callback: EntryCallback<K, V | undefined, [MK, MV]>,
408
- options?: TreeCounterOptions<MK, MV, MR>,
409
- thisArg?: any
347
+ options?: Partial<BinaryTreeOptions<MK, MV, MR>>,
348
+ thisArg?: unknown
410
349
  ): TreeCounter<MK, MV, MR> {
411
- const newTree = new TreeCounter<MK, MV, MR>([], options);
350
+ const out = this._createLike<MK, MV, MR>([], options);
351
+
412
352
  let index = 0;
413
353
  for (const [key, value] of this) {
414
- newTree.add(callback.call(thisArg, key, value, index++, this));
354
+ out.add(callback.call(thisArg, key, value, index++, this));
415
355
  }
416
- return newTree;
356
+ return out;
417
357
  }
418
358
 
419
359
  /**
420
- * The function `keyValueNodeEntryRawToNodeAndValue` takes in a key, value, and count and returns a
421
- * node based on the input.
422
- * @param {K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined} keyNodeOrEntry - The parameter
423
- * `keyNodeOrEntry` can be of type `R` or `K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined`.
424
- * @param {V} [value] - The `value` parameter is an optional value that represents the value
425
- * associated with the key in the node. It is used when creating a new node or updating the value of
426
- * an existing node.
427
- * @param [count=1] - The `count` parameter is an optional parameter that specifies the number of
428
- * times the key-value pair should be added to the data structure. If not provided, it defaults to 1.
429
- * @returns either a TreeCounterNode<K, V> object or undefined.
360
+ * Deep copy this tree, preserving map mode and aggregate counts.
361
+ * @remarks Time O(N), Space O(N)
362
+ * @returns A deep copy of this tree.
363
+ */
364
+ override clone(): this {
365
+ const out = this._createInstance<K, V, R>();
366
+ this._clone(out as unknown as any);
367
+ (out as any)._count = (this as any)._count;
368
+ return out as unknown as this;
369
+ }
370
+
371
+ /**
372
+ * (Protected) Create an empty instance of the same concrete class.
373
+ * @remarks Time O(1), Space O(1)
374
+ * @template TK
375
+ * @template TV
376
+ * @template TR
377
+ * @param [options] - Optional constructor options for the like-kind instance.
378
+ * @returns An empty like-kind instance.
379
+ */
380
+ protected override _createInstance<TK = K, TV = V, TR extends object = R>(
381
+ options?: Partial<BSTOptions<TK, TV, TR>>
382
+ ): this {
383
+ const Ctor = this.constructor as unknown as new (
384
+ iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,
385
+ opts?: BSTOptions<TK, TV, TR>
386
+ ) => this;
387
+ return new Ctor([], { ...this._snapshotOptions<TK, TV, TR>(), ...(options ?? {}) }) as unknown as this;
388
+ }
389
+
390
+ /**
391
+ * (Protected) Create a like-kind instance and seed it from an iterable.
392
+ * @remarks Time O(N log N), Space O(N)
393
+ * @template TK
394
+ * @template TV
395
+ * @template TR
396
+ * @param iter - Iterable used to seed the new tree.
397
+ * @param [options] - Options merged with the current snapshot.
398
+ * @returns A like-kind TreeCounter built from the iterable.
399
+ */
400
+ protected override _createLike<TK = K, TV = V, TR extends object = R>(
401
+ iter: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR> = [],
402
+ options?: Partial<BSTOptions<TK, TV, TR>>
403
+ ): TreeCounter<TK, TV, TR> {
404
+ const Ctor = this.constructor as unknown as new (
405
+ iter?: Iterable<TK | BSTNode<TK, TV> | [TK | null | undefined, TV | undefined] | null | undefined | TR>,
406
+ opts?: BSTOptions<TK, TV, TR>
407
+ ) => TreeCounter<TK, TV, TR>;
408
+ return new Ctor(iter as unknown as Iterable<TK | any>, {
409
+ ...this._snapshotOptions<TK, TV, TR>(),
410
+ ...(options ?? {})
411
+ });
412
+ }
413
+
414
+ /**
415
+ * (Protected) Normalize input into a node plus its effective value and count.
416
+ * @remarks Time O(1), Space O(1)
417
+ * @param keyNodeOrEntry - Key, node, or [key, value] entry.
418
+ * @param [value] - Value used when a bare key is provided.
419
+ * @param [count] - Count increment to apply (default 1).
420
+ * @returns Tuple [node, value] where node may be undefined.
430
421
  */
431
422
  protected override _keyValueNodeOrEntryToNodeAndValue(
432
423
  keyNodeOrEntry: K | TreeCounterNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,
@@ -441,25 +432,18 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
441
432
  const [key, entryValue] = keyNodeOrEntry;
442
433
  if (key === undefined || key === null) return [undefined, undefined];
443
434
  const finalValue = value ?? entryValue;
444
- return [this.createNode(key, finalValue, 'BLACK', count), finalValue];
435
+ return [this._createNode(key, finalValue, 'BLACK', count), finalValue];
445
436
  }
446
437
 
447
- return [this.createNode(keyNodeOrEntry, value, 'BLACK', count), value];
438
+ return [this._createNode(keyNodeOrEntry, value, 'BLACK', count), value];
448
439
  }
449
440
 
450
441
  /**
451
- * Time Complexity: O(1)
452
- * Space Complexity: O(1)
453
- *
454
- * The `_swapProperties` function swaps the properties (key, value, count, color) between two nodes
455
- * in a binary search tree.
456
- * @param {R | BSTNOptKeyOrNode<K, TreeCounterNode<K, V>>} srcNode - The `srcNode` parameter represents the source node
457
- * that will be swapped with the `destNode`. It can be either an instance of the `R` class or an
458
- * instance of the `BSTNOptKeyOrNode<K, TreeCounterNode<K, V>>` class.
459
- * @param {R | BSTNOptKeyOrNode<K, TreeCounterNode<K, V>>} destNode - The `destNode` parameter represents the destination
460
- * node where the properties will be swapped with the source node.
461
- * @returns The method is returning the `destNode` after swapping its properties with the `srcNode`.
462
- * If either `srcNode` or `destNode` is undefined, it returns undefined.
442
+ * (Protected) Swap keys/values/counters between the source and destination nodes.
443
+ * @remarks Time O(1), Space O(1)
444
+ * @param srcNode - Source node (or key) whose properties will be moved.
445
+ * @param destNode - Destination node (or key) to receive properties.
446
+ * @returns Destination node after swap, or undefined.
463
447
  */
464
448
  protected override _swapProperties(
465
449
  srcNode: BSTNOptKeyOrNode<K, TreeCounterNode<K, V>>,
@@ -469,7 +453,7 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
469
453
  destNode = this.ensureNode(destNode);
470
454
  if (srcNode && destNode) {
471
455
  const { key, value, count, color } = destNode;
472
- const tempNode = this.createNode(key, value, color, count);
456
+ const tempNode = this._createNode(key, value, color, count);
473
457
  if (tempNode) {
474
458
  tempNode.color = color;
475
459
 
@@ -490,16 +474,13 @@ export class TreeCounter<K = any, V = any, R = object, MK = any, MV = any, MR =
490
474
  }
491
475
 
492
476
  /**
493
- * Time Complexity: O(1)
494
- * Space Complexity: O(1)
495
- *
496
- * The function replaces an old node with a new node and updates the count property of the new node.
497
- * @param {TreeCounterNode<K, V>} oldNode - The `oldNode` parameter is the node that you want to replace in the data
498
- * structure.
499
- * @param {TreeCounterNode<K, V>} newNode - The `newNode` parameter is an instance of the `TreeCounterNode<K, V>` class.
500
- * @returns The method is returning the result of calling the `_replaceNode` method from the
501
- * superclass, which is of type `TreeCounterNode<K, V>`.
477
+ * (Protected) Replace one node by another and adjust counters accordingly.
478
+ * @remarks Time O(1), Space O(1)
479
+ * @param oldNode - Node being replaced.
480
+ * @param newNode - Replacement node.
481
+ * @returns The new node after replacement.
502
482
  */
483
+
503
484
  protected override _replaceNode(
504
485
  oldNode: TreeCounterNode<K, V>,
505
486
  newNode: TreeCounterNode<K, V>