Class BST<K, V, R>

Represents a Binary Search Tree (BST). Keys are ordered, allowing for faster search operations compared to a standard Binary Tree.

// basic BST creation and add operation
// Create a simple BST with numeric keys
const bst = new BST<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);

bst.print();
// _______8__________
// / \
// ___4___ ____12_____
// / \ / \
// _2_ _6_ _10__ _14__
// / \ / \ / \ / \
// 1 3 5 7 9 11 13 15__
// \
// 16

// Verify size
console.log(bst.size); // 16;

// Add new elements
bst.add(17);
bst.add(0);
console.log(bst.size); // 18;

// Verify keys are searchable
console.log(bst.has(11)); // true;
console.log(bst.has(100)); // false;
// BST delete and search after deletion
const bst = new BST<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);

// Delete a leaf node
bst.delete(1);
console.log(bst.has(1)); // false;

// Delete a node with one child
bst.delete(2);
console.log(bst.has(2)); // false;

// Delete a node with two children
bst.delete(3);
console.log(bst.has(3)); // false;

// Size decreases with each deletion
console.log(bst.size); // 13;

// Other nodes remain searchable
console.log(bst.has(11)); // true;
console.log(bst.has(15)); // true;
// Merge 3 sorted datasets
const dataset1 = new BST<number, string>([
[1, 'A'],
[7, 'G']
]);
const dataset2 = [
[2, 'B'],
[6, 'F']
];
const dataset3 = new BST<number, string>([
[3, 'C'],
[5, 'E'],
[4, 'D']
]);

// Merge datasets into a single BinarySearchTree
const merged = new BST<number, string>(dataset1);
merged.addMany(dataset2);
merged.merge(dataset3);

// Verify merged dataset is in sorted order
console.log([...merged.values()]); // ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
// BST with custom objects for expression evaluation
interface Expression {
id: number;
operator: string;
precedence: number;
}

// BST efficiently stores and retrieves operators by precedence
const operatorTree = new BST<number, Expression>(
[
[1, { id: 1, operator: '+', precedence: 1 }],
[2, { id: 2, operator: '*', precedence: 2 }],
[3, { id: 3, operator: '/', precedence: 2 }],
[4, { id: 4, operator: '-', precedence: 1 }],
[5, { id: 5, operator: '^', precedence: 3 }]
],
{ isMapMode: false }
);

console.log(operatorTree.size); // 5;

// Quick lookup of operators
const mult = operatorTree.get(2);
console.log(mult?.operator); // '*';
console.log(mult?.precedence); // 2;

// Check if operator exists
console.log(operatorTree.has(5)); // true;
console.log(operatorTree.has(99)); // false;

// Retrieve operator by precedence level
const expNode = operatorTree.getNode(3);
console.log(expNode?.key); // 3;
console.log(expNode?.value?.precedence); // 2;

// Delete operator and verify
operatorTree.delete(1);
console.log(operatorTree.has(1)); // false;
console.log(operatorTree.size); // 4;

// Get tree height for optimization analysis
const treeHeight = operatorTree.getHeight();
console.log(treeHeight); // > 0;

// Remaining operators are still accessible
const remaining = operatorTree.get(2);
console.log(remaining); // defined;
// Find lowest common ancestor
const bst = new BST<number>([20, 10, 30, 5, 15, 25, 35, 3, 7, 12, 18]);

// LCA helper function
const findLCA = (num1: number, num2: number): number | undefined => {
const path1 = bst.getPathToRoot(num1);
const path2 = bst.getPathToRoot(num2);
// Find the first common ancestor
return findFirstCommon(path1, path2);
};

function findFirstCommon(arr1: (number | undefined)[], arr2: (number | undefined)[]): number | undefined {
for (const num of arr1) {
if (arr2.indexOf(num) !== -1) {
return num;
}
}
return undefined;
}

// Assertions
console.log(findLCA(3, 10)); // 7;
console.log(findLCA(5, 35)); // 15;
console.log(findLCA(20, 30)); // 25;

Type Parameters

  • K = any

    The type of the key.

  • V = any

    The type of the value.

  • R = any

    The type of the raw data object (if using toEntryFn).

    1. Node Order: Each node's left child has a lesser value, and the right child has a greater value.
    2. Unique Keys: No duplicate keys in a standard BST.
    3. Efficient Search: Enables quick search, minimum, and maximum operations.
    4. Inorder Traversal: Yields nodes in ascending order.
    5. Logarithmic Operations: Ideal operations like insertion, deletion, and searching are O(log n) time-efficient.
    6. Balance Variability: Can become unbalanced; special types maintain balance.
    7. No Auto-Balancing: Standard BSTs don't automatically balance themselves.

Hierarchy (view full)

Implements

  • IBinaryTree<K, V, R>

Constructors

  • Creates an instance of BST.

    Type Parameters

    • K = any
    • V = any
    • R = any

    Parameters

    • OptionalkeysNodesEntriesOrRaws: Iterable<
          | undefined
          | null
          | K
          | R
          | [undefined | null | K, undefined | V]
          | BSTNode<any, any>, any, any> = []

      An iterable of items to add.

    • Optionaloptions: BSTOptions<K, V, R>

      Configuration options for the BST, including comparator.

    Returns BST<K, V, R>

    Time O(N log N) or O(N^2) depending on isBalanceAdd in addMany and input order. Space O(N).

Properties

_comparator: Comparator<K>

The comparator function used to determine the order of keys in the tree.

Time O(1) Space O(1)

Accessors

  • get isDuplicate(): boolean
  • Gets whether the tree allows duplicate keys.

    Returns boolean

    True if duplicates are allowed, false otherwise.

    Time O(1)

  • get isMapMode(): boolean
  • Gets whether the tree is in Map mode.

    Returns boolean

    True if in Map mode, false otherwise.

    In Map mode (default), values are stored in an external Map, and nodes only hold keys. If false, values are stored directly on the nodes. Time O(1)

  • get size(): number
  • Gets the number of nodes in the tree.

    Returns number

    The size of the tree.

    Time O(1)

  • get store(): Map<K, undefined | V>
  • Gets the external value store (used in Map mode).

    Returns Map<K, undefined | V>

    The map storing key-value pairs.

    Time O(1)

  • get toEntryFn(): undefined | ToEntryFn<K, V, R>
  • Gets the function used to convert raw data objects (R) into [key, value] entries.

    Returns undefined | ToEntryFn<K, V, R>

    The conversion function.

    Time O(1)

Methods

  • (Protected) Core bound search implementation supporting all parameter types. Unified logic for both lowerBound and upperBound. Resolves various input types (Key, Node, Entry, Predicate) using parent class utilities.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>

      The key, node, entry, or predicate function to search for.

    • isLower: boolean

      True for lowerBound (>=), false for upperBound (>).

    • iterationType: IterationType

      The iteration type (RECURSIVE or ITERATIVE).

    Returns undefined | BSTNode<K, V>

    The first matching node, or undefined if no such node exists.

  • (Protected) Binary search for bound by key with pruning optimization. Performs standard BST binary search, choosing left or right subtree based on comparator result. For lowerBound: finds first node where key >= target. For upperBound: finds first node where key > target.

    Parameters

    • key: K

      The target key to search for.

    • isLower: boolean

      True for lowerBound (>=), false for upperBound (>).

    • iterationType: IterationType

      The iteration type (RECURSIVE or ITERATIVE).

    Returns undefined | BSTNode<K, V>

    The first node matching the bound condition, or undefined if none exists.

  • (Protected) In-order traversal search by predicate. Falls back to linear in-order traversal when predicate-based search is required. Returns the first node that satisfies the predicate function. Note: Predicate-based search cannot leverage BST's binary search optimization. Time Complexity: O(n) since it may visit every node.

    Parameters

    • predicate: NodePredicate<BSTNode<K, V>>

      The predicate function to test nodes.

    • iterationType: IterationType

      The iteration type (RECURSIVE or ITERATIVE).

    Returns undefined | BSTNode<K, V>

    The first node satisfying predicate, or undefined if none found.

  • (Protected) Compares two keys using the tree's comparator and reverse setting.

    Parameters

    • a: K

      The first key.

    • b: K

      The second key.

    Returns number

    A number (1, -1, or 0) representing the comparison.

    Time O(1) Space O(1)

  • (Protected) Creates the default comparator function for keys that don't have a custom comparator.

    Returns Comparator<K>

    The default comparator function.

    Time O(1) Space O(1)

  • (Protected) Creates a new instance of the same BST constructor, potentially with different generic types.

    Type Parameters

    • TK = K
    • TV = V
    • TR = R

    Parameters

    • Optionaliter: Iterable<
          | undefined
          | null
          | TK
          | TR
          | BSTNode<TK, TV>
          | [undefined | null | TK, undefined | TV], any, any> = []

      An iterable to populate the new BST.

    • Optionaloptions: Partial<BSTOptions<TK, TV, TR>>

      Options for the new BST.

    Returns BST<TK, TV, TR>

    A new BST.

    Time O(N log N) or O(N^2) (from constructor) due to processing the iterable.

  • (Private) Deletes a node by its key.

    Parameters

    • key: K

      The key of the node to delete.

    Returns boolean

    True if the node was found and deleted, false otherwise.

    Standard BST deletion algorithm. Time O(log N), O(N) worst-case. Space O(1).

  • Type Parameters

    Parameters

    • callback: C

      Function to call on nodes.

    • Optionalpattern: DFSOrderPattern

      Traversal order.

    • OptionalonlyOne: boolean

      Stop after first match.

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      Starting node.

    • OptionaliterationType: IterationType

      Traversal method.

    • OptionalincludeNull: boolean

      Include nulls.

    • OptionalshouldVisitLeft: ((node: undefined | null | BinaryTreeNode<K, V>) => boolean)

      Predicate to traverse left.

        • (node): boolean
        • Parameters

          Returns boolean

    • OptionalshouldVisitRight: ((node: undefined | null | BinaryTreeNode<K, V>) => boolean)

      Predicate to traverse right.

        • (node): boolean
        • Parameters

          Returns boolean

    • OptionalshouldVisitRoot: ((node: undefined | null | BinaryTreeNode<K, V>) => boolean)

      Predicate to visit root.

        • (node): boolean
        • Parameters

          Returns boolean

    • OptionalshouldProcessRoot: ((node: undefined | null | BinaryTreeNode<K, V>) => boolean)

      Predicate to process root.

        • (node): boolean
        • Parameters

          Returns boolean

    Returns ReturnType<C>[]

    Array of callback results.

  • (Protected) Binary search for floor by key with pruning optimization. Performs standard BST binary search, choosing left or right subtree based on comparator result. Finds first node where key <= target.

    Parameters

    • key: K

      The target key to search for.

    • iterationType: IterationType

      The iteration type (RECURSIVE or ITERATIVE).

    Returns undefined | BSTNode<K, V>

    The first node with key <= target, or undefined if none exists.

    Time O(h) where h is tree height.

  • (Protected) In-order traversal search for floor by predicate. Falls back to linear in-order traversal when predicate-based search is required. Returns the last node that satisfies the predicate function.

    Parameters

    • predicate: NodePredicate<BSTNode<K, V>>

      The predicate function to test nodes.

    • iterationType: IterationType

      The iteration type (RECURSIVE or ITERATIVE).

    Returns undefined | BSTNode<K, V>

    The last node satisfying predicate (highest key), or undefined if none found.

    Time Complexity: O(n) since it may visit every node. Space Complexity: O(h) for recursion, O(h) for iterative stack.

  • (Protected) Gets the iterator for the tree (default in-order).

    Parameters

    • Optionalnode: null | BinaryTreeNode<K, V> = ...

      The node to start iteration from.

    Returns IterableIterator<[K, undefined | V], any, any>

    An iterator for [key, value] pairs.

    Time O(N) for full iteration. O(H) to get the first element. Space O(H) for the iterative stack. O(H) for recursive stack.

  • (Protected) Converts a key, node, or entry into a standardized [node, value] tuple.

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]

      The input item.

    • Optionalvalue: V

      An optional value (used if input is just a key).

    Returns [OptNode<BSTNode<K, V>>, undefined | V]

    A tuple of [node, value].

    Time O(1)

  • (Protected) Binary search for lower by key with pruning optimization. Performs standard BST binary search, choosing left or right subtree based on comparator result. Finds first node where key < target.

    Parameters

    • key: K

      The target key to search for.

    • iterationType: IterationType

      The iteration type (RECURSIVE or ITERATIVE).

    Returns undefined | BSTNode<K, V>

    The first node with key < target, or undefined if none exists.

    Time O(h) where h is tree height.

  • (Protected) In-order traversal search for lower by predicate. Falls back to linear in-order traversal when predicate-based search is required. Returns the node that satisfies the predicate and appears last in in-order traversal.

    Parameters

    • predicate: NodePredicate<BSTNode<K, V>>

      The predicate function to test nodes.

    • iterationType: IterationType

      The iteration type (RECURSIVE or ITERATIVE).

    Returns undefined | BSTNode<K, V>

    The last node satisfying predicate (highest key < target), or undefined if none found.

    Time Complexity: O(n) since it may visit every node. Space Complexity: O(h) for recursion, O(h) for iterative stack.

  • (Protected) Sets a value in the external store (Map mode).

    Parameters

    • key: undefined | null | K

      The key.

    • value: undefined | V

      The value.

    Returns false | Map<K, undefined | V>

    True if successful.

    Time O(1) (average for Map.set).

  • Default iterator yielding [key, value] entries.

    Parameters

    • Rest...args: any[]

    Returns IterableIterator<[K, undefined | V], any, any>

    Iterator of [K, V].

    Time O(n) to iterate, Space O(1)

  • Adds a new node to the BST based on key comparison.

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]

      The key, node, or entry to add.

    • Optionalvalue: V

      The value, if providing just a key.

    Returns boolean

    True if the addition was successful, false otherwise.

    Time O(log N), where H is tree height. O(N) worst-case (unbalanced tree), O(log N) average. Space O(1).

  • Adds multiple items to the tree.

    Parameters

    • keysNodesEntriesOrRaws: Iterable<R | BTNRep<K, V, BSTNode<K, V>>, any, any>

      An iterable of items to add.

    • Optionalvalues: Iterable<undefined | V, any, any>

      An optional parallel iterable of values.

    • OptionalisBalanceAdd: boolean = true

      If true, builds a balanced tree from the items.

    • OptionaliterationType: IterationType = ...

      The traversal method for balanced add (recursive or iterative).

    Returns boolean[]

    An array of booleans indicating the success of each individual add operation.

    If isBalanceAdd is true, sorts the input and builds a balanced tree. Time O(N log N) (due to sort and balanced add). If false, adds items one by one. Time O(N * H), which is O(N^2) worst-case. Space O(N) for sorting and recursion/iteration stack.

  • Returns the first key with a value >= target. Equivalent to Java TreeMap.ceiling. Time Complexity: O(log n) average, O(h) worst case. Space Complexity: O(h) for recursion, O(1) for iteration.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>

    Returns undefined | K

  • Returns the first node with a key >= target and applies callback. Time Complexity: O(log n) average, O(h) worst case. Space Complexity: O(h) for recursion, O(1) for iteration.

    Type Parameters

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>
    • callback: C
    • OptionaliterationType: IterationType

    Returns ReturnType<C>

  • Clones the tree.

    Returns this

    A new, cloned instance of the tree.

    Time O(N * M), where N is the number of nodes and M is the tree size during insertion (due to bfs + add, and add is O(M)). Space O(N) for the new tree and the BFS queue.

  • Creates a new, empty tree of the same type and configuration.

    Parameters

    • Optionaloptions: Partial<BinaryTreeOptions<K, V, R>>

      Optional overrides for the new tree's options.

    Returns this

    A new, empty tree instance.

    Time O(1) (excluding options cloning), Space O(1)

  • Deletes a node from the tree.

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The node to delete.

    Returns BinaryTreeDeleteResult<BinaryTreeNode<K, V>>[]

    An array containing deletion results (for compatibility with self-balancing trees).

    Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation finds the node, and if it has two children, swaps it with the rightmost node of its left subtree (in-order predecessor) before deleting. Time O(N) in the worst case. O(N) to find the node (getNode) and O(H) (which is O(N) worst-case) to find the rightmost node. Space O(1) (if getNode is iterative, which it is).

  • Deletes nodes that match a key, node, entry, predicate, or range.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>
          | Range<K>

      The search criteria. Can be one of:

      • A key (type K): searches for exact key match using the comparator.
      • A BSTNode: searches for the matching node in the tree.
      • An entry tuple: searches for the key-value pair.
      • A NodePredicate function: tests each node and returns true for matches.
      • A Range object: searches for nodes whose keys fall within the specified range (inclusive/exclusive based on range settings).
      • null or undefined: treated as no match, returns empty results.
    • onlyOne: boolean = false

      If true, stops the search after finding the first match and only deletes that one node. If false (default), searches for and deletes all matching nodes.

    • startNode:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to start the search from. Can be:

      • A key, node, or entry: the method resolves it to a node and searches from that subtree.
      • null or undefined: defaults to the root, searching the entire tree.
      • Default value: this._root (the tree's root).
    • iterationType: IterationType = ...

      Controls the internal traversal implementation:

      • 'RECURSIVE': uses recursive function calls for traversal.
      • 'ITERATIVE': uses explicit stack-based iteration.
      • Default: this.iterationType (the tree's default iteration mode).

    Returns BinaryTreeDeleteResult<BSTNode<K, V>>[]

    A Map<K, boolean> containing the deletion results:

    • Key: the matched node's key.
    • Value: true if the deletion succeeded, false if it failed (e.g., key not found during deletion phase).
    • If no nodes match the search criteria, the returned map is empty.

    Time Complexity: O(N) for search + O(M log N) for M deletions, where N is tree size. Space Complexity: O(M) for storing matched nodes and result map.

  • Ensures the input is a node. If it's a key or entry, it searches for the node.

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]

      The item to resolve to a node.

    • OptionaliterationType: IterationType = ...

      The traversal method to use if searching.

    Returns OptNode<BSTNode<K, V>>

    The resolved node, or undefined if not found.

    Time O(log N) (height of the tree), O(N) worst-case.

  • Iterate over [key, value] pairs (may yield undefined values).

    Returns IterableIterator<[K, undefined | V], any, any>

    Iterator of [K, V | undefined].

    Time O(n), Space O(1)

  • Test whether all entries satisfy the predicate.

    Parameters

    • predicate: EntryCallback<K, undefined | V, boolean>

      (key, value, index, self) => boolean.

    • OptionalthisArg: any

      Optional this for callback.

    Returns boolean

    true if all pass; otherwise false.

    Time O(n), Space O(1)

  • Creates a new tree containing only the entries that satisfy the predicate.

    Parameters

    • predicate: EntryCallback<K, undefined | V, boolean>

      A function to test each [key, value] pair.

    • OptionalthisArg: unknown

      this context for the predicate.

    Returns this

    A new, filtered tree.

    Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion (O(N) iteration + O(M) add for each item). Space O(N) for the new tree.

  • Find the first entry that matches a predicate.

    Parameters

    • callbackfn: EntryCallback<K, undefined | V, boolean>

      (key, value, index, self) => boolean.

    • OptionalthisArg: any

      Optional this for callback.

    Returns undefined | [K, undefined | V]

    Matching [key, value] or undefined.

    Time O(n), Space O(1)

  • Returns the first key with a value <= target. Equivalent to Java TreeMap.floor. Time Complexity: O(log n) average, O(h) worst case. Space Complexity: O(h) for recursion, O(1) for iteration.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>

    Returns undefined | K

  • Returns the first node with a key <= target and applies callback. Time Complexity: O(log n) average, O(h) worst case. Space Complexity: O(h) for recursion, O(1) for iteration.

    Type Parameters

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>
    • callback: C
    • OptionaliterationType: IterationType

    Returns ReturnType<C>

  • Visit each entry, left-to-right.

    Parameters

    • callbackfn: EntryCallback<K, undefined | V, void>

      (key, value, index, self) => void.

    • OptionalthisArg: any

      Optional this for callback.

    Returns void

    Time O(n), Space O(1)

  • Gets the value associated with a key.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The key, node, or entry to get the value for.

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to start searching from (if not in Map mode).

    • OptionaliterationType: IterationType = ...

      The traversal method (if not in Map mode).

    Returns undefined | V

    The associated value, or undefined.

    Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(1) if in Map mode. O(N) if not in Map mode (uses getNode). Space O(1) if in Map mode. O(H) or O(N) otherwise.

  • Gets the depth of a node (distance from startNode).

    Parameters

    • dist:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The node to find the depth of.

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to measure depth from (defaults to root).

    Returns number

    The depth (0 if dist is startNode).

    Time O(H), where H is the depth of the dist node relative to startNode. O(N) worst-case. Space O(1).

  • Gets the maximum height of the tree (longest path from startNode to a leaf).

    Parameters

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to start measuring from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns number

    The height ( -1 for an empty tree, 0 for a single-node tree).

    Time O(N), as it must visit every node. Space O(H) for recursive stack (O(N) worst-case) or O(N) for iterative stack (storing node + depth).

  • Gets the minimum height of the tree (shortest path from startNode to a leaf).

    Parameters

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to start measuring from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns number

    The minimum height (-1 for empty, 0 for single node).

    Time O(N), as it must visit every node. Space O(H) for recursive stack (O(N) worst-case) or O(N) for iterative (due to depths Map).

  • Gets the first node matching a predicate.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>

      The key, node, entry, or predicate function to search for.

    • OptionalstartNode: BSTNOptKeyOrNode<K, BSTNode<K, V>> = ...

      The node to start the search from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns OptNode<BSTNode<K, V>>

    The first matching node, or undefined if not found.

    Time O(log N) if searching by key, O(N) if searching by predicate. Space O(log N) or O(N).

  • Gets all nodes matching a predicate.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BinaryTreeNode<K, V>>

      The key, node, entry, or predicate function to search for.

    • OptionalonlyOne: boolean

      If true, stops after finding the first match.

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The node to start the search from.

    • OptionaliterationType: IterationType

      The traversal method.

    Returns BinaryTreeNode<K, V>[]

    An array of matching nodes.

    Time O(N) (via search). Space O(H) or O(N) (via search).

  • Checks if a node matching the predicate exists in the tree.

    Parameters

    • OptionalkeyNodeEntryOrPredicate:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BinaryTreeNode<K, V>>

      The key, node, entry, or predicate to check for.

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The node to start the search from.

    • OptionaliterationType: IterationType

      The traversal method.

    Returns boolean

    True if a matching node exists, false otherwise.

    Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(N) in the worst case (via search). Space O(H) or O(N) (via search).

  • Returns the first key with a value > target. Equivalent to Java TreeMap.higher. Time Complexity: O(log n) average, O(h) worst case. Space Complexity: O(h) for recursion, O(1) for iteration.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>

    Returns undefined | K

  • Returns the first node with a key > target and applies callback. Time Complexity: O(log n) average, O(h) worst case. Space Complexity: O(h) for recursion, O(1) for iteration.

    Type Parameters

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>
    • callback: C
    • OptionaliterationType: IterationType

    Returns ReturnType<C>

  • Checks if the tree meets the AVL balance condition (height difference <= 1).

    Parameters

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns boolean

    True if the tree is AVL balanced, false otherwise.

    Time O(N), as it must visit every node to compute height. Space O(log N) for recursion or O(N) for iterative map.

  • Checks if the tree is a valid Binary Search Tree (BST).

    Parameters

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to start checking from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns boolean

    True if it's a valid BST, false otherwise.

    Time O(N), as it must visit every node. Space O(H) for the call stack (recursive) or explicit stack (iterative), where H is the tree height (O(N) worst-case).

  • Checks if the given item is a [key, value] entry pair.

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The item to check.

    Returns keyNodeOrEntry is BTNEntry<K, V>

    True if it's an entry, false otherwise.

    Time O(1), Space O(1)

  • Checks if a node is a leaf (has no real children).

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The node to check.

    Returns boolean

    True if the node is a leaf, false otherwise.

    Time O(N) if a key/entry is passed (due to ensureNode). O(1) if a node is passed. Space O(1) or O(H) (from ensureNode).

  • Checks if the given item is the sentinel NIL node.

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The item to check.

    Returns boolean

    True if it's the NIL node, false otherwise.

    Time O(1), Space O(1)

  • Checks if the given item is a BSTNode instance.

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]

      The item to check.

    Returns keyNodeOrEntry is BSTNode<K, V>

    True if it's a BSTNode, false otherwise.

    Time O(1), Space O(1)

  • Checks if the tree is perfectly balanced.

    Parameters

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to start checking from.

    Returns boolean

    True if perfectly balanced, false otherwise.

    A tree is perfectly balanced if the difference between min and max height is at most 1. Time O(N), as it requires two full traversals (getMinHeight and getHeight). Space O(H) or O(N) (from height calculation).

  • Checks if the given item is a Range object.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
          | Range<K>
          | NodePredicate<BinaryTreeNode<K, V>>

      The item to check.

    Returns keyNodeEntryOrPredicate is Range<K>

    True if it's a Range, false otherwise.

    Time O(1), Space O(1)

  • Checks if the given item is a raw data object (R) that needs conversion via toEntryFn.

    Parameters

    • keyNodeEntryOrRaw:
          | undefined
          | null
          | K
          | R
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The item to check.

    Returns keyNodeEntryOrRaw is R

    True if it's a raw object, false otherwise.

    Time O(1), Space O(1)

  • Returns (undefined | K)[]

  • Type Parameters

    Parameters

    • callback: C
    • OptionallesserOrGreater: number
    • OptionaltargetNode:
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
    • OptionaliterationType: IterationType

    Returns ReturnType<C>[]

  • Returns the first key with a value < target. Equivalent to Java TreeMap.lower. Time Complexity: O(log n) average, O(h) worst case. Space Complexity: O(h) for recursion, O(1) for iteration.

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>

    Returns undefined | K

  • Returns the first node with a key < target and applies callback. Time Complexity: O(log n) average, O(h) worst case. Space Complexity: O(h) for recursion, O(1) for iteration.

    Type Parameters

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>
    • callback: C
    • OptionaliterationType: IterationType

    Returns ReturnType<C>

  • Creates a new BST by mapping each [key, value] pair to a new entry.

    Type Parameters

    • MK = K

      New key type.

    • MV = V

      New value type.

    • MR = any

      New raw type.

    Parameters

    • callback: EntryCallback<K, undefined | V, [MK, MV]>

      A function to map each [key, value] pair.

    • Optionaloptions: Partial<BSTOptions<MK, MV, MR>>

      Options for the new BST.

    • OptionalthisArg: unknown

      this context for the callback.

    Returns BST<MK, MV, MR>

    A new, mapped BST.

    Time O(N * H), where N is nodes in this tree, and H is height of the new tree during insertion. Space O(N) for the new tree.

  • Merges another tree into this one by adding all its nodes.

    Parameters

    Returns void

    Time O(N * M), same as addMany, where N is the size of anotherTree and M is the size of this tree. Space O(M) (from add).

  • Rebuilds the tree to be perfectly balanced.

    Parameters

    • OptionaliterationType: IterationType = ...

      The traversal method for the initial node export.

    Returns boolean

    True if successful, false if the tree was empty.

    Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.

  • Prints a visual representation of the tree to the console.

    Parameters

    • Optionaloptions: BinaryTreePrintOptions

      Options to control the output.

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to start printing from.

    Returns void

    Time O(N) (via toVisual). Space O(N*H) or O(N^2) (via toVisual).

  • Reduce entries into a single accumulator.

    Type Parameters

    • U

    Parameters

    • callbackfn: ReduceEntryCallback<K, undefined | V, U>

      (acc, value, key, index, self) => acc.

    • initialValue: U

      Initial accumulator.

    Returns U

    Final accumulator.

    Time O(n), Space O(1)

  • Clears the tree and refills it with new items.

    Parameters

    • keysNodesEntriesOrRaws: Iterable<
          | undefined
          | null
          | K
          | R
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V], any, any>

      An iterable of items to add.

    • Optionalvalues: Iterable<undefined | V, any, any>

      An optional parallel iterable of values.

    Returns void

    Time O(N) (for clear) + O(N * M) (for addMany) = O(N * M). Space O(M) (from addMany).

  • Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>
          | Range<K>
    • OptionalonlyOne: boolean

    Returns (undefined | K)[]

  • Type Parameters

    Parameters

    • keyNodeEntryOrPredicate:
          | undefined
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
          | NodePredicate<BSTNode<K, V>>
          | Range<K>
    • onlyOne: boolean
    • callback: C
    • OptionalstartNode:
          | null
          | K
          | BSTNode<K, V>
          | [undefined | null | K, undefined | V]
    • OptionaliterationType: IterationType

    Returns ReturnType<C>[]

  • Adds or updates a new node to the tree.

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The key, node, or entry to add or update.

    • Optionalvalue: V

      The value, if providing just a key.

    Returns boolean

    True if the addition was successful, false otherwise.

    Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation adds the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).

  • Adds or updates multiple items to the tree.

    Parameters

    • keysNodesEntriesOrRaws: Iterable<
          | undefined
          | null
          | K
          | R
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V], any, any>

      An iterable of items to add or update.

    • Optionalvalues: Iterable<undefined | V, any, any>

      An optional parallel iterable of values.

    Returns boolean[]

    An array of booleans indicating the success of each individual add operation.

    Time O(N * M), where N is the number of items to add and M is the size of the tree at insertion (due to O(M) add operation). Space O(M) (from add) + O(N) (for the inserted array).

  • Test whether any entry satisfies the predicate.

    Parameters

    • predicate: EntryCallback<K, undefined | V, boolean>

      (key, value, index, self) => boolean.

    • OptionalthisArg: any

      Optional this for callback.

    Returns boolean

    true if any passes; otherwise false.

    Time O(n), Space O(1)

  • Generates a string representation of the tree for visualization.

    Parameters

    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V] = ...

      The node to start printing from.

    • Optionaloptions: BinaryTreePrintOptions

      Options to control the output (e.g., show nulls).

    Returns string

    The string representation of the tree.

    Time O(N), visits every node. Space O(N*H) or O(N^2) in the worst case, as the string width can grow significantly.