MCPcopy Create free account
hub / github.com/denoland/std / BinarySearchTree

Class BinarySearchTree

data_structures/binary_search_tree.ts:93–758  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

91 * @typeparam T The type of the values stored in the binary search tree.
92 */
93export class BinarySearchTree<T> implements Iterable<T> {
94 #root: BinarySearchNode<T> | null = null;
95 #size = 0;
96 #compare: (a: T, b: T) => number;
97
98 /**
99 * Construct an empty binary search tree.
100 *
101 * To create a binary search tree from an array like, an iterable object, or an
102 * existing binary search tree, use the {@link BinarySearchTree.from} method.
103 *
104 * @param compare A custom comparison function to sort the values in the tree.
105 * By default, the values are sorted in ascending order.
106 */
107 constructor(compare: (a: T, b: T) => number = ascend) {
108 if (typeof compare !== "function") {
109 throw new TypeError(
110 "Cannot construct a BinarySearchTree: the 'compare' parameter is not a function, did you mean to call BinarySearchTree.from?",
111 );
112 }
113 this.#compare = compare;
114 }
115
116 static {
117 internals.getRoot = <T>(tree: BinarySearchTree<T>) => tree.#root;
118 internals.setRoot = <T>(
119 tree: BinarySearchTree<T>,
120 node: BinarySearchNode<T> | null,
121 ) => {
122 tree.#root = node;
123 };
124 internals.getCompare = <T>(tree: BinarySearchTree<T>) => tree.#compare;
125 internals.findNode = <T>(
126 tree: BinarySearchTree<T>,
127 value: T,
128 ): BinarySearchNode<T> | null => tree.#findNode(value);
129 internals.rotateNode = <T>(
130 tree: BinarySearchTree<T>,
131 node: BinarySearchNode<T>,
132 direction: Direction,
133 ) => tree.#rotateNode(node, direction);
134 internals.insertNode = <T>(
135 tree: BinarySearchTree<T>,
136 Node: typeof BinarySearchNode,
137 value: T,
138 ): BinarySearchNode<T> | null => tree.#insertNode(Node, value);
139 internals.removeNode = <T>(
140 tree: BinarySearchTree<T>,
141 node: BinarySearchNode<T>,
142 ): BinarySearchNode<T> | null => tree.#removeNode(node);
143 internals.setSize = <T>(tree: BinarySearchTree<T>, size: number) =>
144 tree.#size = size;
145 }
146
147 /**
148 * Creates a new binary search tree from an array like, an iterable object,
149 * or an existing binary search tree.
150 *

Callers

nothing calls this directly

Calls 4

#rotateNodeMethod · 0.80
#insertNodeMethod · 0.80
#removeNodeMethod · 0.80
#findNodeMethod · 0.45

Tested by

no test coverage detected