data-structure-typed 1.18.5 → 1.18.7

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