Class TreeMultiMap<K, V, R>

Red-Black Tree–based multimap (key → array of values). Preserves O(log N) updates and supports map-like mode.

Time O(1), Space O(1)

// players ranked by score with their equipment
type Equipment = {
name: string; // Equipment name
quality: 'legendary' | 'epic' | 'rare' | 'common';
level: number;
};

type Player = {
name: string;
score: number;
equipments: Equipment[];
};

// Mock player data with their scores and equipment
const players: Player[] = [
{
name: 'DragonSlayer',
score: 8750,
equipments: [
{ name: 'AWM', quality: 'legendary', level: 85 },
{ name: 'Level 3 Helmet', quality: 'epic', level: 80 },
{ name: 'Extended Quickdraw Mag', quality: 'rare', level: 75 },
{ name: 'Compensator', quality: 'epic', level: 78 },
{ name: 'Vertical Grip', quality: 'rare', level: 72 }
]
},
{
name: 'ShadowNinja',
score: 7200,
equipments: [
{ name: 'M416', quality: 'epic', level: 75 },
{ name: 'Ghillie Suit', quality: 'rare', level: 70 },
{ name: 'Red Dot Sight', quality: 'common', level: 65 },
{ name: 'Extended QuickDraw Mag', quality: 'rare', level: 68 }
]
},
{
name: 'RuneMaster',
score: 9100,
equipments: [
{ name: 'KAR98K', quality: 'legendary', level: 90 },
{ name: 'Level 3 Vest', quality: 'legendary', level: 85 },
{ name: 'Holographic Sight', quality: 'epic', level: 82 },
{ name: 'Suppressor', quality: 'legendary', level: 88 },
{ name: 'Level 3 Backpack', quality: 'epic', level: 80 }
]
},
{
name: 'BattleKing',
score: 8500,
equipments: [
{ name: 'AUG', quality: 'epic', level: 82 },
{ name: 'Red Dot Sight', quality: 'rare', level: 75 },
{ name: 'Extended Mag', quality: 'common', level: 70 },
{ name: 'Tactical Stock', quality: 'rare', level: 76 }
]
},
{
name: 'SniperElite',
score: 7800,
equipments: [
{ name: 'M24', quality: 'legendary', level: 88 },
{ name: 'Compensator', quality: 'epic', level: 80 },
{ name: 'Scope 8x', quality: 'legendary', level: 85 },
{ name: 'Level 2 Helmet', quality: 'rare', level: 75 }
]
},
{
name: 'RushMaster',
score: 7500,
equipments: [
{ name: 'Vector', quality: 'rare', level: 72 },
{ name: 'Level 2 Helmet', quality: 'common', level: 65 },
{ name: 'Quickdraw Mag', quality: 'common', level: 60 },
{ name: 'Laser Sight', quality: 'rare', level: 68 }
]
},
{
name: 'GhostWarrior',
score: 8200,
equipments: [
{ name: 'SCAR-L', quality: 'epic', level: 78 },
{ name: 'Extended Quickdraw Mag', quality: 'rare', level: 70 },
{ name: 'Holographic Sight', quality: 'epic', level: 75 },
{ name: 'Suppressor', quality: 'rare', level: 72 },
{ name: 'Vertical Grip', quality: 'common', level: 65 }
]
},
{
name: 'DeathDealer',
score: 7300,
equipments: [
{ name: 'SKS', quality: 'epic', level: 76 },
{ name: 'Holographic Sight', quality: 'rare', level: 68 },
{ name: 'Extended Mag', quality: 'common', level: 65 }
]
},
{
name: 'StormRider',
score: 8900,
equipments: [
{ name: 'MK14', quality: 'legendary', level: 92 },
{ name: 'Level 3 Backpack', quality: 'legendary', level: 85 },
{ name: 'Scope 8x', quality: 'epic', level: 80 },
{ name: 'Suppressor', quality: 'legendary', level: 88 },
{ name: 'Tactical Stock', quality: 'rare', level: 75 }
]
},
{
name: 'CombatLegend',
score: 7600,
equipments: [
{ name: 'UMP45', quality: 'rare', level: 74 },
{ name: 'Level 2 Vest', quality: 'common', level: 67 },
{ name: 'Red Dot Sight', quality: 'common', level: 62 },
{ name: 'Extended Mag', quality: 'rare', level: 70 }
]
}
];

// Create a TreeMultiMap for player rankings
const playerRankings = new TreeMultiMap<number, Equipment, Player>(players, {
toEntryFn: ({ score, equipments }) => [score, equipments],
isMapMode: false
});

const topPlayersEquipments = playerRankings.rangeSearch([8900, 10000], node => playerRankings.get(node));
console.log(topPlayersEquipments); // [
// [
// {
// name: 'MK14',
// quality: 'legendary',
// level: 92
// },
// { name: 'Level 3 Backpack', quality: 'legendary', level: 85 },
// {
// name: 'Scope 8x',
// quality: 'epic',
// level: 80
// },
// { name: 'Suppressor', quality: 'legendary', level: 88 },
// {
// name: 'Tactical Stock',
// quality: 'rare',
// level: 75
// }
// ],
// [
// { name: 'KAR98K', quality: 'legendary', level: 90 },
// {
// name: 'Level 3 Vest',
// quality: 'legendary',
// level: 85
// },
// { name: 'Holographic Sight', quality: 'epic', level: 82 },
// {
// name: 'Suppressor',
// quality: 'legendary',
// level: 88
// },
// { name: 'Level 3 Backpack', quality: 'epic', level: 80 }
// ]
// ]

Type Parameters

  • K = any
  • V = any
  • R extends object = object

Hierarchy (view full)

Implements

  • IBinaryTree<K, V[], R>

Constructors

  • Create a TreeMultiMap and optionally bulk-insert items.

    Type Parameters

    • K = any
    • V = any
    • R extends object = object

    Parameters

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

      Iterable of keys/nodes/entries/raw items to insert.

    • Optionaloptions: TreeMultiMapOptions<K, V[], R>

      Options for TreeMultiMap (comparator, reverse, map mode).

    Returns TreeMultiMap<K, V, R>

    New TreeMultiMap instance.

    Time O(N log N), Space O(N)

Properties

_comparator: Comparator<K> = ...

The default comparator function.

Time O(1) (or O(C) if specifyComparable is used, C is complexity of that function).

Accessors

  • get comparator(): Comparator<K>
  • Gets the comparator function used by the tree.

    Returns Comparator<K>

    The comparator function.

    Time O(1)

  • 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 isReverse(): boolean
  • Gets whether the tree's comparison logic is reversed.

    Returns boolean

    True if the tree is reversed (e.g., a max-heap logic).

    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 specifyComparable(): undefined | ((key: K) => Comparable)
  • Gets the function used to extract a comparable value from a complex key.

    Returns undefined | ((key: K) => Comparable)

    The key-to-comparable conversion function.

    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) 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) (or O(C) if specifyComparable is used).

  • 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) 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) 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)

  • Insert or replace an entry using BST order and red-black fix-up.

    Parameters

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

      Key, node, or [key, value] entry to insert.

    Returns boolean

    True if inserted or updated; false if ignored.

    Time O(log n), Space O(1)

  • Parameters

    • key: K
    • value: V

    Returns boolean

  • 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.

  • Performs a Breadth-First Search (BFS) or Level-Order traversal.

    Type Parameters

    • C extends NodeCallback<BSTNode<K, V[]>>

      The type of the callback function.

    Parameters

    • Optionalcallback: C = ...

      Function to call on each node.

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

      The node to start from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns ReturnType<C>[]

    An array of callback results.

    Time O(N), visits every node. Space O(N) in the worst case for the queue.

  • 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)

  • Delete a node by key/node/entry and rebalance as needed.

    Parameters

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

      Key, node, or [key, value] entry identifying the node to delete.

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

    Array with deletion metadata (removed node, rebalancing hint if any).

    Time O(log n), Space O(1)

  • Delete a single value from the bucket at a given key. Removes the key if the bucket becomes empty.

    Parameters

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

      Key, node, or [key, values] entry to locate the bucket.

    • value: V

      Value to remove from the bucket.

    Returns boolean

    True if the value was removed; false if not found.

    Time O(log N), Space O(1)

  • Deletes the first node found that satisfies the predicate.

    Parameters

    • predicate: ((key: K, value: undefined | V[], index: number, tree: this) => boolean)

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

        • (key, value, index, tree): boolean
        • Parameters

          • key: K
          • value: undefined | V[]
          • index: number
          • tree: this

          Returns boolean

    Returns boolean

    True if a node was deleted, false otherwise.

    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.

  • Performs a Depth-First Search (DFS) traversal.

    Type Parameters

    • C extends NodeCallback<BSTNode<K, V[]>>

      The type of the callback function.

    Parameters

    • Optionalcallback: C = ...

      Function to call on each node.

    • Optionalpattern: DFSOrderPattern = 'IN'

      The traversal order ('IN', 'PRE', 'POST').

    • OptionalonlyOne: boolean = false

      If true, stops after the first callback.

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

      The node to start from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns ReturnType<C>[]

    An array of callback results.

    Time O(N), visits every node. Space O(log N) for the call/explicit stack. O(N) worst-case.

  • 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)

  • 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).

  • Finds the leftmost node in a subtree (the node with the smallest key in a BST).

    Type Parameters

    • C extends NodeCallback<undefined | BinaryTreeNode<K, V[]>>

      The type of the callback function.

    Parameters

    • Optionalcallback: C = ...

      A function to call on the leftmost node.

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

      The subtree root to search from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns ReturnType<C>

    The callback result for the leftmost node.

    Time O(H), where H is the height of the left spine. O(N) worst-case. Space O(H) for recursive/trampoline stack.

  • 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).

  • Gets the path from a given node up to the root.

    Type Parameters

    • C extends NodeCallback<undefined | BinaryTreeNode<K, V[]>>

      The type of the callback function.

    Parameters

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

      The node to start the path from.

    • Optionalcallback: C = ...

      A function to call on each node in the path.

    • OptionalisReverse: boolean = false

      If true, returns the path from root-to-node.

    Returns ReturnType<C>[]

    An array of callback results.

    Time O(H), where H is the depth of the beginNode. O(N) worst-case. Space O(H) for the result array.

  • Finds the rightmost node in a subtree (the node with the largest key in a BST).

    Type Parameters

    • C extends NodeCallback<undefined | BinaryTreeNode<K, V[]>>

      The type of the callback function.

    Parameters

    • Optionalcallback: C = ...

      A function to call on the rightmost node.

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

      The subtree root to search from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns ReturnType<C>

    The callback result for the rightmost node.

    Time O(H), where H is the height of the right spine. O(N) worst-case. Space O(H) for recursive/trampoline stack.

  • 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).

  • 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 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[]]
          | NodePredicate<BinaryTreeNode<K, V[]>>
          | Range<K>

      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)

  • Finds all leaf nodes in the tree.

    Type Parameters

    • C extends NodeCallback<null | BinaryTreeNode<K, V[]>>

      The type of the callback function.

    Parameters

    • Optionalcallback: C = ...

      Function to call on each leaf node.

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

      The node to start from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns ReturnType<C>[]

    An array of callback results.

    Time O(N), visits every node. Space O(H) for recursive stack or O(N) for iterative queue.

  • Traverses the tree and returns nodes that are lesser or greater than a target node.

    Type Parameters

    • C extends NodeCallback<BSTNode<K, V[]>>

      The type of the callback function.

    Parameters

    • Optionalcallback: C = ...

      Function to call on matching nodes.

    • OptionallesserOrGreater: CP = -1

      1 for lesser, 1 for greater, 0 for equal.

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

      The node to compare against.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns ReturnType<C>[]

    An array of callback results.

    Time O(N), as it performs a full traversal. Space O(log N) or O(N).

  • Returns a 2D array of nodes, grouped by level.

    Type Parameters

    • C extends NodeCallback<BSTNode<K, V[]>>

      The type of the callback function.

    Parameters

    • Optionalcallback: C = ...

      Function to call on each node.

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

      The node to start from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns ReturnType<C>[][]

    A 2D array of callback results.

    Time O(N), visits every node. Space O(N) for the result array and the queue/stack.

  • 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).

  • Type Parameters

    • C extends NodeCallback<BinaryTreeNode<K, V[]>>

      The type of the callback function.

    Parameters

    • Optionalcallback: C

      Function to call on each node.

    • Optionalpattern: DFSOrderPattern

      The traversal order ('IN', 'PRE', 'POST').

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

      The node to start from.

    Returns ReturnType<C>[]

    An array of callback results.

  • 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).

  • Performs an optimized search for nodes within a given key range.

    Type Parameters

    • C extends NodeCallback<BSTNode<K, V[]>>

      The type of the callback function.

    Parameters

    • range: Range<K> | [K, K]

      A Range object or a [low, high] tuple.

    • Optionalcallback: C = ...

      A function to call on matching nodes.

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

      The node to start the search from.

    • OptionaliterationType: IterationType = ...

      The traversal method.

    Returns ReturnType<C>[]

    An array of callback results.

    Time O(H + M), where H is tree height and M is the number of matches.

  • 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).

  • Searches the tree for nodes matching a predicate, key, or range.

    Type Parameters

    • C extends NodeCallback<BSTNode<K, V[]>>

      The type of the callback function.

    Parameters

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

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

    • OptionalonlyOne: boolean = false

      If true, stops after finding the first match.

    • Optionalcallback: C = ...

      A function to call on matching nodes.

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

      The node to start the search from.

    • OptionaliterationType: IterationType = ...

      Whether to use 'RECURSIVE' or 'ITERATIVE' search.

    Returns ReturnType<C>[]

    An array of results from the callback function for each matching node.

    This is an optimized search for a BST. If searching by key or range, it prunes branches. Time O(H + M) for key/range search (H=height, M=matches). O(N) for predicate search. Space O(log N) for the stack.

  • 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.