binary-tree-typed 2.2.3 → 2.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,11 +7,10 @@
7
7
  */
8
8
 
9
9
  import type {
10
- BinaryTreeOptions,
10
+ BinaryTreeDeleteResult,
11
11
  BSTNOptKeyOrNode,
12
12
  BSTOptions,
13
13
  BTNRep,
14
- Comparable,
15
14
  Comparator,
16
15
  CP,
17
16
  DFSOrderPattern,
@@ -355,18 +354,22 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
355
354
  * @param [options] - Configuration options for the BST, including comparator.
356
355
  */
357
356
  constructor(
358
- keysNodesEntriesOrRaws: Iterable<
359
- K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R
360
- > = [],
357
+ keysNodesEntriesOrRaws: Iterable<K | BSTNode | [K | null | undefined, V | undefined] | null | undefined | R> = [],
361
358
  options?: BSTOptions<K, V, R>
362
359
  ) {
363
360
  super([], options);
364
361
 
365
362
  if (options) {
366
- const { specifyComparable, isReverse } = options;
367
- if (typeof specifyComparable === 'function') this._specifyComparable = specifyComparable;
368
- if (isReverse !== undefined) this._isReverse = isReverse;
363
+ // Use the 'in' operator to check if the field is present
364
+ if ('comparator' in options && options.comparator !== undefined) {
365
+ this._comparator = options.comparator;
366
+ } else {
367
+ this._comparator = this._createDefaultComparator();
368
+ }
369
+ } else {
370
+ this._comparator = this._createDefaultComparator();
369
371
  }
372
+
370
373
  if (keysNodesEntriesOrRaws) this.addMany(keysNodesEntriesOrRaws);
371
374
  }
372
375
 
@@ -382,42 +385,12 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
382
385
  return this._root;
383
386
  }
384
387
 
385
- protected _isReverse: boolean = false;
386
-
387
388
  /**
388
- * Gets whether the tree's comparison logic is reversed.
389
- * @remarks Time O(1)
390
- *
391
- * @returns True if the tree is reversed (e.g., a max-heap logic).
392
- */
393
- get isReverse(): boolean {
394
- return this._isReverse;
395
- }
389
+ * The comparator function used to determine the order of keys in the tree.
396
390
 
397
- /**
398
- * The default comparator function.
399
- * @remarks Time O(1) (or O(C) if `specifyComparable` is used, C is complexity of that function).
391
+ * @remarks Time O(1) Space O(1)
400
392
  */
401
- protected _comparator: Comparator<K> = (a: K, b: K): number => {
402
- if (isComparable(a) && isComparable(b)) {
403
- if (a > b) return 1;
404
- if (a < b) return -1;
405
- return 0;
406
- }
407
- if (this._specifyComparable) {
408
- const va = this._specifyComparable(a);
409
- const vb = this._specifyComparable(b);
410
- if (va > vb) return 1;
411
- if (va < vb) return -1;
412
- return 0;
413
- }
414
- if (typeof a === 'object' || typeof b === 'object') {
415
- throw TypeError(
416
- `When comparing object types, a custom specifyComparable must be defined in the constructor's options.`
417
- );
418
- }
419
- return 0;
420
- };
393
+ protected _comparator: Comparator<K>;
421
394
 
422
395
  /**
423
396
  * Gets the comparator function used by the tree.
@@ -429,18 +402,6 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
429
402
  return this._comparator;
430
403
  }
431
404
 
432
- protected _specifyComparable?: (key: K) => Comparable;
433
-
434
- /**
435
- * Gets the function used to extract a comparable value from a complex key.
436
- * @remarks Time O(1)
437
- *
438
- * @returns The key-to-comparable conversion function.
439
- */
440
- get specifyComparable(): ((key: K) => Comparable) | undefined {
441
- return this._specifyComparable;
442
- }
443
-
444
405
  /**
445
406
  * (Protected) Creates a new BST node.
446
407
  * @remarks Time O(1), Space O(1)
@@ -489,7 +450,7 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
489
450
  * @returns True if the key is valid, false otherwise.
490
451
  */
491
452
  override isValidKey(key: any): key is K {
492
- return isComparable(key, this._specifyComparable !== undefined);
453
+ return isComparable(key);
493
454
  }
494
455
 
495
456
  /**
@@ -625,8 +586,8 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
625
586
  if (isRange) {
626
587
  // Range search: Only go left if the current key is >= the lower bound
627
588
  const range = keyNodeEntryOrPredicate as Range<K>;
628
- const leftS = this.isReverse ? range.high : range.low;
629
- const leftI = this.isReverse ? range.includeHigh : range.includeLow;
589
+ const leftS = range.low;
590
+ const leftI = range.includeLow;
630
591
  return (leftI && this._compare(cur.key, leftS) >= 0) || (!leftI && this._compare(cur.key, leftS) > 0);
631
592
  }
632
593
  if (!isRange && !this._isPredicate(keyNodeEntryOrPredicate)) {
@@ -643,8 +604,8 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
643
604
  if (isRange) {
644
605
  // Range search: Only go right if current key <= upper bound
645
606
  const range = keyNodeEntryOrPredicate as Range<K>;
646
- const rightS = this.isReverse ? range.low : range.high;
647
- const rightI = this.isReverse ? range.includeLow : range.includeHigh;
607
+ const rightS = range.high;
608
+ const rightI = range.includeHigh;
648
609
  return (rightI && this._compare(cur.key, rightS) <= 0) || (!rightI && this._compare(cur.key, rightS) < 0);
649
610
  }
650
611
  if (!isRange && !this._isPredicate(keyNodeEntryOrPredicate)) {
@@ -891,6 +852,164 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
891
852
  return this._bound(keyNodeEntryOrPredicate, false, iterationType);
892
853
  }
893
854
 
855
+ /**
856
+ * Returns the first node with a key greater than or equal to the given key.
857
+ * This is equivalent to Java TreeMap.ceilingEntry().
858
+ * Supports RECURSIVE and ITERATIVE implementations.
859
+ * @remarks Time Complexity: O(log n) on average, O(h) where h is tree height.
860
+ * Space Complexity: O(h) for recursion, O(1) for iteration.
861
+ *
862
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
863
+ * @param [iterationType=this.iterationType] - The iteration type (RECURSIVE or ITERATIVE).
864
+ * @returns The first node with key >= given key, or undefined if no such node exists.
865
+ */
866
+ ceilingEntry(
867
+ keyNodeEntryOrPredicate:
868
+ | K
869
+ | BSTNode<K, V>
870
+ | [K | null | undefined, V | undefined]
871
+ | null
872
+ | undefined
873
+ | NodePredicate<BSTNode<K, V>>,
874
+ iterationType: IterationType = this.iterationType
875
+ ): BSTNode<K, V> | undefined {
876
+ return this.lowerBound(keyNodeEntryOrPredicate, iterationType);
877
+ }
878
+
879
+ /**
880
+ * Returns the first node with a key strictly greater than the given key.
881
+ * This is equivalent to Java TreeMap.higherEntry().
882
+ * Supports RECURSIVE and ITERATIVE implementations.
883
+ * @remarks Time Complexity: O(log n) on average, O(h) where h is tree height.
884
+ * Space Complexity: O(h) for recursion, O(1) for iteration.
885
+ *
886
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
887
+ * @param [iterationType=this.iterationType] - The iteration type (RECURSIVE or ITERATIVE).
888
+ * @returns The first node with key > given key, or undefined if no such node exists.
889
+ */
890
+ higherEntry(
891
+ keyNodeEntryOrPredicate:
892
+ | K
893
+ | BSTNode<K, V>
894
+ | [K | null | undefined, V | undefined]
895
+ | null
896
+ | undefined
897
+ | NodePredicate<BSTNode<K, V>>,
898
+ iterationType: IterationType = this.iterationType
899
+ ): BSTNode<K, V> | undefined {
900
+ return this.upperBound(keyNodeEntryOrPredicate, iterationType);
901
+ }
902
+
903
+ /**
904
+ * Returns the first node with a key less than or equal to the given key.
905
+ * This is equivalent to Java TreeMap.floorEntry().
906
+ * Supports RECURSIVE and ITERATIVE implementations.
907
+ * @remarks Time Complexity: O(log n) on average, O(h) where h is tree height.
908
+ * Space Complexity: O(h) for recursion, O(1) for iteration.
909
+ *
910
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
911
+ * @param [iterationType=this.iterationType] - The iteration type (RECURSIVE or ITERATIVE).
912
+ * @returns The first node with key <= given key, or undefined if no such node exists.
913
+ */
914
+ floorEntry(
915
+ keyNodeEntryOrPredicate:
916
+ | K
917
+ | BSTNode<K, V>
918
+ | [K | null | undefined, V | undefined]
919
+ | null
920
+ | undefined
921
+ | NodePredicate<BSTNode<K, V>>,
922
+ iterationType: IterationType = this.iterationType
923
+ ): BSTNode<K, V> | undefined {
924
+ if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined) {
925
+ return undefined;
926
+ }
927
+
928
+ // Check if input is a predicate function first
929
+ if (this._isPredicate(keyNodeEntryOrPredicate)) {
930
+ return this._floorByPredicate(keyNodeEntryOrPredicate, iterationType);
931
+ }
932
+
933
+ // Resolve input to a comparable key
934
+ let targetKey: K | undefined;
935
+ if (this.isNode(keyNodeEntryOrPredicate)) {
936
+ // Input is a BSTNode - extract its key
937
+ targetKey = keyNodeEntryOrPredicate.key;
938
+ } else if (this.isEntry(keyNodeEntryOrPredicate)) {
939
+ // Input is a [key, value] entry - extract the key
940
+ const key = keyNodeEntryOrPredicate[0];
941
+ if (key === null || key === undefined) {
942
+ return undefined;
943
+ }
944
+ targetKey = key;
945
+ } else {
946
+ // Input is a raw key
947
+ targetKey = keyNodeEntryOrPredicate;
948
+ }
949
+
950
+ // Execute key-based search with binary search optimization
951
+ if (targetKey !== undefined) {
952
+ return this._floorByKey(targetKey, iterationType);
953
+ }
954
+
955
+ return undefined;
956
+ }
957
+
958
+ /**
959
+ * Returns the first node with a key strictly less than the given key.
960
+ * This is equivalent to Java TreeMap.lowerEntry().
961
+ * Supports RECURSIVE and ITERATIVE implementations.
962
+ * @remarks Time Complexity: O(log n) on average, O(h) where h is tree height.
963
+ * Space Complexity: O(h) for recursion, O(1) for iteration.
964
+ *
965
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
966
+ * @param [iterationType=this.iterationType] - The iteration type (RECURSIVE or ITERATIVE).
967
+ * @returns The first node with key < given key, or undefined if no such node exists.
968
+ */
969
+ lowerEntry(
970
+ keyNodeEntryOrPredicate:
971
+ | K
972
+ | BSTNode<K, V>
973
+ | [K | null | undefined, V | undefined]
974
+ | null
975
+ | undefined
976
+ | NodePredicate<BSTNode<K, V>>,
977
+ iterationType: IterationType = this.iterationType
978
+ ): BSTNode<K, V> | undefined {
979
+ if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === undefined) {
980
+ return undefined;
981
+ }
982
+
983
+ // Check if input is a predicate function first
984
+ if (this._isPredicate(keyNodeEntryOrPredicate)) {
985
+ return this._lowerByPredicate(keyNodeEntryOrPredicate, iterationType);
986
+ }
987
+
988
+ // Resolve input to a comparable key
989
+ let targetKey: K | undefined;
990
+ if (this.isNode(keyNodeEntryOrPredicate)) {
991
+ // Input is a BSTNode - extract its key
992
+ targetKey = keyNodeEntryOrPredicate.key;
993
+ } else if (this.isEntry(keyNodeEntryOrPredicate)) {
994
+ // Input is a [key, value] entry - extract the key
995
+ const key = keyNodeEntryOrPredicate[0];
996
+ if (key === null || key === undefined) {
997
+ return undefined;
998
+ }
999
+ targetKey = key;
1000
+ } else {
1001
+ // Input is a raw key
1002
+ targetKey = keyNodeEntryOrPredicate;
1003
+ }
1004
+
1005
+ // Execute key-based search with binary search optimization
1006
+ if (targetKey !== undefined) {
1007
+ return this._lowerByKey(targetKey, iterationType);
1008
+ }
1009
+
1010
+ return undefined;
1011
+ }
1012
+
894
1013
  /**
895
1014
  * Traverses the tree and returns nodes that are lesser or greater than a target node.
896
1015
  * @remarks Time O(N), as it performs a full traversal. Space O(log N) or O(N).
@@ -1037,7 +1156,7 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
1037
1156
  */
1038
1157
  override map<MK = K, MV = V, MR = any>(
1039
1158
  callback: EntryCallback<K, V | undefined, [MK, MV]>,
1040
- options?: Partial<BinaryTreeOptions<MK, MV, MR>>,
1159
+ options?: Partial<BSTOptions<MK, MV, MR>>,
1041
1160
  thisArg?: unknown
1042
1161
  ): BST<MK, MV, MR> {
1043
1162
  const out = this._createLike<MK, MV, MR>([], options);
@@ -1050,34 +1169,326 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
1050
1169
  }
1051
1170
 
1052
1171
  /**
1053
- * Deletes the first node found that satisfies the predicate.
1054
- * @remarks Performs an in-order traversal. Time O(N) worst-case (O(log N) to find + O(log N) to delete). Space O(log N) for stack.
1172
+ * Deletes nodes that match a key, node, entry, predicate, or range.
1173
+ *
1174
+ * @remarks
1175
+ * Time Complexity: O(N) for search + O(M log N) for M deletions, where N is tree size.
1176
+ * Space Complexity: O(M) for storing matched nodes and result map.
1177
+ *
1178
+ * @template K - The key type.
1179
+ * @template V - The value type.
1180
+ *
1181
+ * @param keyNodeEntryOrPredicate - The search criteria. Can be one of:
1182
+ * - A key (type K): searches for exact key match using the comparator.
1183
+ * - A BSTNode: searches for the matching node in the tree.
1184
+ * - An entry tuple: searches for the key-value pair.
1185
+ * - A NodePredicate function: tests each node and returns true for matches.
1186
+ * - A Range object: searches for nodes whose keys fall within the specified range (inclusive/exclusive based on range settings).
1187
+ * - null or undefined: treated as no match, returns empty results.
1055
1188
  *
1056
- * @param predicate - A function to test each [key, value] pair.
1057
- * @returns True if a node was deleted, false otherwise.
1189
+ * @param onlyOne - If true, stops the search after finding the first match and only deletes that one node.
1190
+ * If false (default), searches for and deletes all matching nodes.
1191
+ *
1192
+ * @param startNode - The node to start the search from. Can be:
1193
+ * - A key, node, or entry: the method resolves it to a node and searches from that subtree.
1194
+ * - null or undefined: defaults to the root, searching the entire tree.
1195
+ * - Default value: this._root (the tree's root).
1196
+ *
1197
+ * @param iterationType - Controls the internal traversal implementation:
1198
+ * - 'RECURSIVE': uses recursive function calls for traversal.
1199
+ * - 'ITERATIVE': uses explicit stack-based iteration.
1200
+ * - Default: this.iterationType (the tree's default iteration mode).
1201
+ *
1202
+ * @returns A Map<K, boolean> containing the deletion results:
1203
+ * - Key: the matched node's key.
1204
+ * - Value: true if the deletion succeeded, false if it failed (e.g., key not found during deletion phase).
1205
+ * - If no nodes match the search criteria, the returned map is empty.
1058
1206
  */
1059
- deleteWhere(predicate: (key: K, value: V | undefined, index: number, tree: this) => boolean): boolean {
1060
- const stack: Array<BSTNode<K, V> | null | undefined> = [];
1061
- let cur = this._root as BSTNode<K, V> | null | undefined;
1062
- let index = 0;
1207
+ deleteWhere(
1208
+ keyNodeEntryOrPredicate:
1209
+ | K
1210
+ | BSTNode<K, V>
1211
+ | [K | null | undefined, V | undefined]
1212
+ | null
1213
+ | undefined
1214
+ | NodePredicate<BSTNode<K, V>>
1215
+ | Range<K>,
1216
+ onlyOne = false,
1217
+ startNode: K | BSTNode<K, V> | [K | null | undefined, V | undefined] | null | undefined = this._root,
1218
+ iterationType: IterationType = this.iterationType
1219
+ ): BinaryTreeDeleteResult<BSTNode<K, V>>[] {
1220
+ const toDelete = this.search(keyNodeEntryOrPredicate, onlyOne, node => node, startNode, iterationType);
1221
+
1222
+ let results: BinaryTreeDeleteResult<BSTNode<K, V>>[] = [];
1223
+ for (const node of toDelete) {
1224
+ const deleteInfo = this.delete(node);
1225
+ results = results.concat(deleteInfo);
1226
+ }
1063
1227
 
1064
- // In-order traversal to find the node
1065
- while (stack.length > 0 || cur !== undefined) {
1066
- while (cur !== undefined && cur !== null) {
1067
- stack.push(cur);
1068
- cur = cur.left as BSTNode<K, V> | null | undefined;
1228
+ return results;
1229
+ }
1230
+
1231
+ /**
1232
+ * (Protected) Creates the default comparator function for keys that don't have a custom comparator.
1233
+ * @remarks Time O(1) Space O(1)
1234
+ * @returns The default comparator function.
1235
+ */
1236
+ protected _createDefaultComparator(): Comparator<K> {
1237
+ return (a: K, b: K): number => {
1238
+ debugger;
1239
+ // If both keys are comparable (primitive types), use direct comparison
1240
+ if (isComparable(a) && isComparable(b)) {
1241
+ if (a > b) return 1;
1242
+ if (a < b) return -1;
1243
+ return 0;
1069
1244
  }
1070
- const node = stack.pop() as BSTNode<K, V> | undefined;
1071
- if (!node) break;
1072
1245
 
1073
- const key = node.key as K;
1074
- const val = node.value as V | undefined;
1075
- if (predicate(key, val, index++, this)) {
1076
- return this._deleteByKey(key); // Found, now delete
1246
+ // If keys are objects and no comparator is provided, throw an error
1247
+ if (typeof a === 'object' || typeof b === 'object') {
1248
+ throw TypeError(
1249
+ `When comparing object type keys, a custom comparator must be provided in the constructor's options!`
1250
+ );
1077
1251
  }
1078
- cur = node.right as BSTNode<K, V> | null | undefined;
1252
+
1253
+ // Default: keys are equal (fallback case)
1254
+ return 0;
1255
+ };
1256
+ }
1257
+
1258
+ /**
1259
+ * (Protected) Binary search for floor by key with pruning optimization.
1260
+ * Performs standard BST binary search, choosing left or right subtree based on comparator result.
1261
+ * Finds first node where key <= target.
1262
+ * @remarks Time O(h) where h is tree height.
1263
+ *
1264
+ * @param key - The target key to search for.
1265
+ * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).
1266
+ * @returns The first node with key <= target, or undefined if none exists.
1267
+ */
1268
+ protected _floorByKey(key: K, iterationType: IterationType): BSTNode<K, V> | undefined {
1269
+ if (iterationType === 'RECURSIVE') {
1270
+ // Recursive binary search implementation
1271
+ const dfs = (cur: BSTNode<K, V> | null | undefined): BSTNode<K, V> | undefined => {
1272
+ if (!this.isRealNode(cur)) return undefined;
1273
+
1274
+ const cmp = this.comparator(cur.key!, key);
1275
+
1276
+ if (cmp <= 0) {
1277
+ // Current node satisfies the floor condition (cur.key <= target).
1278
+ // Try to find a larger candidate in the right subtree.
1279
+ const rightResult = dfs(cur.right);
1280
+ return rightResult ?? cur;
1281
+ } else {
1282
+ // Current node is too large, move left to find smaller keys.
1283
+ return dfs(cur.left);
1284
+ }
1285
+ };
1286
+
1287
+ return dfs(this.root);
1288
+ } else {
1289
+ // Iterative binary search implementation
1290
+ let current: BSTNode<K, V> | undefined = this.root;
1291
+ let result: BSTNode<K, V> | undefined = undefined;
1292
+
1293
+ while (this.isRealNode(current)) {
1294
+ const cmp = this.comparator(current.key!, key);
1295
+
1296
+ if (cmp <= 0) {
1297
+ // Current node is a candidate. Save it and try right subtree for a larger key.
1298
+ result = current;
1299
+ current = current.right ?? undefined;
1300
+ } else {
1301
+ // Current node is too large, move left.
1302
+ current = current.left ?? undefined;
1303
+ }
1304
+ }
1305
+
1306
+ return result;
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ * (Protected) In-order traversal search for floor by predicate.
1312
+ * Falls back to linear in-order traversal when predicate-based search is required.
1313
+ * Returns the last node that satisfies the predicate function.
1314
+ * @remarks Time Complexity: O(n) since it may visit every node.
1315
+ * Space Complexity: O(h) for recursion, O(h) for iterative stack.
1316
+ *
1317
+ * @param predicate - The predicate function to test nodes.
1318
+ * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).
1319
+ * @returns The last node satisfying predicate (highest key), or undefined if none found.
1320
+ */
1321
+ protected _floorByPredicate(
1322
+ predicate: NodePredicate<BSTNode<K, V>>,
1323
+ iterationType: IterationType
1324
+ ): BSTNode<K, V> | undefined {
1325
+ if (iterationType === 'RECURSIVE') {
1326
+ // Recursive in-order traversal
1327
+ let result: BSTNode<K, V> | undefined = undefined;
1328
+
1329
+ const dfs = (cur: BSTNode<K, V> | null | undefined): void => {
1330
+ if (!this.isRealNode(cur)) return;
1331
+
1332
+ // In-order: process left subtree first
1333
+ if (this.isRealNode(cur.left)) dfs(cur.left);
1334
+
1335
+ // Check current node
1336
+ if (predicate(cur)) {
1337
+ result = cur;
1338
+ }
1339
+
1340
+ // Process right subtree
1341
+ if (this.isRealNode(cur.right)) dfs(cur.right);
1342
+ };
1343
+
1344
+ dfs(this.root);
1345
+ return result;
1346
+ } else {
1347
+ // Iterative in-order traversal using explicit stack
1348
+ const stack: (BSTNode<K, V> | null | undefined)[] = [];
1349
+ let current: BSTNode<K, V> | null | undefined = this.root;
1350
+ let result: BSTNode<K, V> | undefined = undefined;
1351
+
1352
+ while (stack.length > 0 || this.isRealNode(current)) {
1353
+ if (this.isRealNode(current)) {
1354
+ // Go to the leftmost node
1355
+ stack.push(current);
1356
+ current = current.left;
1357
+ } else {
1358
+ // Pop from stack and process
1359
+ const node = stack.pop();
1360
+ if (!this.isRealNode(node)) break;
1361
+
1362
+ // Check if current node satisfies predicate
1363
+ if (predicate(node)) {
1364
+ result = node;
1365
+ }
1366
+
1367
+ // Visit right subtree
1368
+ current = node.right;
1369
+ }
1370
+ }
1371
+
1372
+ return result;
1373
+ }
1374
+ }
1375
+
1376
+ /**
1377
+ * (Protected) Binary search for lower by key with pruning optimization.
1378
+ * Performs standard BST binary search, choosing left or right subtree based on comparator result.
1379
+ * Finds first node where key < target.
1380
+ * @remarks Time O(h) where h is tree height.
1381
+ *
1382
+ * @param key - The target key to search for.
1383
+ * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).
1384
+ * @returns The first node with key < target, or undefined if none exists.
1385
+ */
1386
+ protected _lowerByKey(key: K, iterationType: IterationType): BSTNode<K, V> | undefined {
1387
+ if (iterationType === 'RECURSIVE') {
1388
+ // Recursive binary search implementation
1389
+ const dfs = (cur: BSTNode<K, V> | null | undefined): BSTNode<K, V> | undefined => {
1390
+ if (!this.isRealNode(cur)) return undefined;
1391
+
1392
+ const cmp = this.comparator(cur.key!, key);
1393
+
1394
+ if (cmp < 0) {
1395
+ // Current node satisfies the lower condition (cur.key < target).
1396
+ // Try to find a larger candidate in the right subtree.
1397
+ const rightResult = dfs(cur.right);
1398
+ return rightResult ?? cur;
1399
+ } else {
1400
+ // Current node is too large or equal, move left to find smaller keys.
1401
+ return dfs(cur.left);
1402
+ }
1403
+ };
1404
+
1405
+ return dfs(this.root);
1406
+ } else {
1407
+ // Iterative binary search implementation
1408
+ let current: BSTNode<K, V> | undefined = this.root;
1409
+ let result: BSTNode<K, V> | undefined = undefined;
1410
+
1411
+ while (this.isRealNode(current)) {
1412
+ const cmp = this.comparator(current.key!, key);
1413
+
1414
+ if (cmp < 0) {
1415
+ // Current node is a candidate. Save it and try right subtree for a larger key.
1416
+ result = current;
1417
+ current = current.right ?? undefined;
1418
+ } else {
1419
+ // Current node is too large or equal, move left.
1420
+ current = current.left ?? undefined;
1421
+ }
1422
+ }
1423
+
1424
+ return result;
1425
+ }
1426
+ }
1427
+
1428
+ /**
1429
+ * (Protected) In-order traversal search for lower by predicate.
1430
+ * Falls back to linear in-order traversal when predicate-based search is required.
1431
+ * Returns the node that satisfies the predicate and appears last in in-order traversal.
1432
+ * @remarks Time Complexity: O(n) since it may visit every node.
1433
+ * Space Complexity: O(h) for recursion, O(h) for iterative stack.
1434
+ *
1435
+ * @param predicate - The predicate function to test nodes.
1436
+ * @param iterationType - The iteration type (RECURSIVE or ITERATIVE).
1437
+ * @returns The last node satisfying predicate (highest key < target), or undefined if none found.
1438
+ */
1439
+ protected _lowerByPredicate(
1440
+ predicate: NodePredicate<BSTNode<K, V>>,
1441
+ iterationType: IterationType
1442
+ ): BSTNode<K, V> | undefined {
1443
+ if (iterationType === 'RECURSIVE') {
1444
+ // Recursive in-order traversal
1445
+ let result: BSTNode<K, V> | undefined = undefined;
1446
+
1447
+ const dfs = (cur: BSTNode<K, V> | null | undefined): void => {
1448
+ if (!this.isRealNode(cur)) return;
1449
+
1450
+ // In-order: process left subtree first
1451
+ if (this.isRealNode(cur.left)) dfs(cur.left);
1452
+
1453
+ // Check current node
1454
+ if (predicate(cur)) {
1455
+ result = cur;
1456
+ }
1457
+
1458
+ // Process right subtree
1459
+ if (this.isRealNode(cur.right)) dfs(cur.right);
1460
+ };
1461
+
1462
+ dfs(this.root);
1463
+ return result;
1464
+ } else {
1465
+ // Iterative in-order traversal using explicit stack
1466
+ const stack: (BSTNode<K, V> | null | undefined)[] = [];
1467
+ let current: BSTNode<K, V> | null | undefined = this.root;
1468
+ let result: BSTNode<K, V> | undefined = undefined;
1469
+
1470
+ while (stack.length > 0 || this.isRealNode(current)) {
1471
+ if (this.isRealNode(current)) {
1472
+ // Go to the leftmost node
1473
+ stack.push(current);
1474
+ current = current.left;
1475
+ } else {
1476
+ // Pop from stack and process
1477
+ const node = stack.pop();
1478
+ if (!this.isRealNode(node)) break;
1479
+
1480
+ // Check if current node satisfies predicate
1481
+ if (predicate(node)) {
1482
+ result = node;
1483
+ }
1484
+
1485
+ // Visit right subtree
1486
+ current = node.right;
1487
+ }
1488
+ }
1489
+
1490
+ return result;
1079
1491
  }
1080
- return false;
1081
1492
  }
1082
1493
 
1083
1494
  /**
@@ -1300,8 +1711,7 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
1300
1711
  protected override _snapshotOptions<TK = K, TV = V, TR = R>(): BSTOptions<TK, TV, TR> {
1301
1712
  return {
1302
1713
  ...super._snapshotOptions<TK, TV, TR>(),
1303
- specifyComparable: this.specifyComparable as BSTOptions<TK, TV, TR>['specifyComparable'],
1304
- isReverse: this.isReverse as BSTOptions<TK, TV, TR>['isReverse']
1714
+ comparator: this._comparator as unknown as BSTOptions<TK, TV, TR>['comparator']
1305
1715
  };
1306
1716
  }
1307
1717
 
@@ -1335,14 +1745,14 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
1335
1745
 
1336
1746
  /**
1337
1747
  * (Protected) Compares two keys using the tree's comparator and reverse setting.
1338
- * @remarks Time O(1) (or O(C) if `specifyComparable` is used).
1748
+ * @remarks Time O(1) Space O(1)
1339
1749
  *
1340
1750
  * @param a - The first key.
1341
1751
  * @param b - The second key.
1342
1752
  * @returns A number (1, -1, or 0) representing the comparison.
1343
1753
  */
1344
1754
  protected _compare(a: K, b: K) {
1345
- return this._isReverse ? -this._comparator(a, b) : this._comparator(a, b);
1755
+ return this._comparator(a, b);
1346
1756
  }
1347
1757
 
1348
1758
  /**
@@ -1352,7 +1762,7 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
1352
1762
  * @param key - The key of the node to delete.
1353
1763
  * @returns True if the node was found and deleted, false otherwise.
1354
1764
  */
1355
- private _deleteByKey(key: K): boolean {
1765
+ protected _deleteByKey(key: K): boolean {
1356
1766
  let node = this._root as BSTNode<K, V> | undefined;
1357
1767
 
1358
1768
  // 1. Find the node