Class BinaryTree<K, V, R>

A general Binary Tree implementation.

This class implements a basic Binary Tree, not a Binary Search Tree. The add operation inserts nodes level-by-level (BFS) into the first available slot.

// determine loan approval using a decision tree
// Decision tree structure
const loanDecisionTree = new BinaryTree<string>(
['stableIncome', 'goodCredit', 'Rejected', 'Approved', 'Rejected'],
{ isDuplicate: true }
);

function determineLoanApproval(
node?: BinaryTreeNode<string> | null,
conditions?: { [key: string]: boolean }
): string {
if (!node) throw new Error('Invalid node');

// If it's a leaf node, return the decision result
if (!node.left && !node.right) return node.key;

// Check if a valid condition exists for the current node's key
return conditions?.[node.key]
? determineLoanApproval(node.left, conditions)
: determineLoanApproval(node.right, conditions);
}

// Test case 1: Stable income and good credit score
console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: true, goodCredit: true })); // 'Approved'

// Test case 2: Stable income but poor credit score
console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: true, goodCredit: false })); // 'Rejected'

// Test case 3: No stable income
console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: false, goodCredit: true })); // 'Rejected'

// Test case 4: No stable income and poor credit score
console.log(determineLoanApproval(loanDecisionTree.root, { stableIncome: false, goodCredit: false })); // 'Rejected'
// evaluate the arithmetic expression represented by the binary tree
const expressionTree = new BinaryTree<number | string>(['+', 3, '*', null, null, 5, '-', null, null, 2, 8]);

function evaluate(node?: BinaryTreeNode<number | string> | null): number {
if (!node) return 0;

if (typeof node.key === 'number') return node.key;

const leftValue = evaluate(node.left); // Evaluate the left subtree
const rightValue = evaluate(node.right); // Evaluate the right subtree

// Perform the operation based on the current node's operator
switch (node.key) {
case '+':
return leftValue + rightValue;
case '-':
return leftValue - rightValue;
case '*':
return leftValue * rightValue;
case '/':
return rightValue !== 0 ? leftValue / rightValue : 0; // Handle division by zero
default:
throw new Error(`Unsupported operator: ${node.key}`);
}
}

console.log(evaluate(expressionTree.root)); // -27

Type Parameters

  • K = any

    The type of the key.

  • V = any

    The type of the value.

  • R extends object = object

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

    1. Two Children Maximum: Each node has at most two children.
    2. Left and Right Children: Nodes have distinct left and right children.
    3. Depth and Height: Depth is the number of edges from the root to a node; height is the maximum depth in the tree.
    4. Subtrees: Each child of a node forms the root of a subtree.
    5. Leaf Nodes: Nodes without children are leaves.

Hierarchy (view full)

Implements

  • IBinaryTree<K, V, R>

Constructors

  • Creates an instance of BinaryTree.

    Type Parameters

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

    Parameters

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

      An iterable of items to add.

    • Optionaloptions: BinaryTreeOptions<K, V, R>

      Configuration options for the tree.

    Returns BinaryTree<K, V, R>

    Time O(N * M), where N is the number of items in keysNodesEntriesOrRaws and M is the tree size at insertion time (due to O(M) add operation). Space O(N) for storing the nodes.

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) Helper for cloning. Performs a BFS and adds all nodes to the new tree.

    Parameters

    • cloned: BinaryTree<K, V, R>

      The new, empty tree instance to populate.

    Returns void

    Time O(N * M) (O(N) BFS + O(M) add for each node).

  • (Protected) Creates a new, empty instance of the same tree constructor.

    Type Parameters

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

    Parameters

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

      Options for the new tree.

    Returns this

    A new, empty tree.

    Time O(1)

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

    Type Parameters

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

    Parameters

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

      An iterable to populate the new tree.

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

      Options for the new tree.

    Returns BinaryTree<TK, TV, TR>

    A new tree.

    Time O(N) (or as per constructor) due to processing the iterable.

  • 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) Recursive helper for toVisual.

    Parameters

    • node: undefined | null | BinaryTreeNode<K, V>

      The current node.

    • options: BinaryTreePrintOptions

      Print options.

    Returns NodeDisplayLayout

    Layout information for this subtree.

    Time O(N), Space O(N*H) or O(N^2)

  • (Protected) Extracts the key from a key, node, or entry.

    Parameters

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

      The item.

    Returns undefined | null | K

    The extracted key.

    Time O(1)

  • (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
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]

      The input item.

    • Optionalvalue: V

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

    Returns [undefined | null | BinaryTreeNode<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).

  • (Protected) Swaps the key/value properties of two nodes.

    Parameters

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

      The source node.

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

      The destination node.

    Returns undefined | BinaryTreeNode<K, V>

    The destNode (now holding srcNode's properties).

    Time O(1)

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

    Parameters

    • keyNodeOrEntry:
          | undefined
          | null
          | K
          | BinaryTreeNode<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), 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 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.

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

  • Type Parameters

    Parameters

    • Optionalcallback: C
    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
    • OptionaliterationType: IterationType
    • OptionalincludeNull: false

    Returns ReturnType<C>[]

  • Type Parameters

    Parameters

    • Optionalcallback: C
    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
    • OptionaliterationType: IterationType
    • OptionalincludeNull: true

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

  • Type Parameters

    Parameters

    • Optionalcallback: C
    • Optionalpattern: DFSOrderPattern
    • OptionalonlyOne: boolean
    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
    • OptionaliterationType: IterationType

    Returns ReturnType<C>[]

  • Type Parameters

    Parameters

    • Optionalcallback: C
    • Optionalpattern: DFSOrderPattern
    • OptionalonlyOne: boolean
    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
    • OptionaliterationType: IterationType
    • OptionalincludeNull: boolean

    Returns ReturnType<C>[]

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

    Parameters

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

      The item to resolve to a node.

    • OptionaliterationType: IterationType = ...

      The traversal method to use if searching.

    Returns undefined | null | BinaryTreeNode<K, V>

    The resolved node, or null/undefined if not found or input is null/undefined.

    Time O(1) if a node is passed. O(N) if a key or entry is passed (due to getNode performing a full search). Space O(1) if iterative search, O(H) if recursive (where H is height, O(N) worst-case).

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

      The key, node, entry, or predicate function to search 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 undefined | null | BinaryTreeNode<K, V>

    The first matching node, or undefined if not found.

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

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

  • Checks if the given item is a "real" node (i.e., not null, undefined, or NIL).

    Parameters

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

      The item to check.

    Returns keyNodeOrEntry is BinaryTreeNode<K, V>

    True if it's a real node, false otherwise.

    Time O(1), Space O(1)

  • Checks if the given item is either a "real" node or null.

    Parameters

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

      The item to check.

    Returns keyNodeOrEntry is null | BinaryTreeNode<K, V>

    True if it's a real node or null, false otherwise.

    Time O(1), Space O(1)

  • Checks if the given key is valid (comparable or null).

    Parameters

    • key: any

      The key to validate.

    Returns key is K

    True if the key is valid, 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.

  • Type Parameters

    Parameters

    • Optionalcallback: C
    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
    • OptionaliterationType: IterationType
    • OptionalincludeNull: false

    Returns ReturnType<C>[][]

  • Type Parameters

    Parameters

    • Optionalcallback: C
    • OptionalstartNode:
          | null
          | K
          | BinaryTreeNode<K, V>
          | [undefined | null | K, undefined | V]
    • OptionaliterationType: IterationType
    • OptionalincludeNull: true

    Returns ReturnType<C>[][]

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

    Type Parameters

    • MK = K

      New key type.

    • MV = V

      New value type.

    • MR extends object = object

      New raw type.

    Parameters

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

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

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

      Options for the new tree.

    • OptionalthisArg: unknown

      this context for the callback.

    Returns BinaryTree<MK, MV, MR>

    A new, mapped tree.

    Time O(N * M), where N is nodes in this tree, and M is size 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).

  • Type Parameters

    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.

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

  • Searches the tree for nodes matching a predicate.

    Type Parameters

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

      The type of the callback function.

    Parameters

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

      The key, node, entry, or predicate function 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
          | BinaryTreeNode<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.

    Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Performs a full DFS (pre-order) scan of the tree. Time O(N), as it may 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).

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