Insert 100,000 keys right into a binary search tree in sorted order and it turns into an inventory 99,999 ranges deep. Insert the identical keys shuffled and the peak stays close to 40. The keys are equivalent and the algorithm is equivalent. Solely the insertion order decides whether or not the tree earns the O(log n) that the textbook guarantees. The identical order additionally decides how costly the fascinating operations are: the predecessor, the successor, the ground, the ceiling and the k-th smallest key, all of that are what a search tree is admittedly for.
This information implements a binary search tree in C, C++, Java, Python and C# and measures what the fundamental descriptions skip. It reveals how the peak collapses underneath sorted enter, what the three delete circumstances value, and what number of comparisons every ordered operation takes on a random tree. Each node additionally shops the scale of its subtree, which makes rank and choose a single stroll down one path. The hand-written tree is then in contrast with the ordered containers the usual libraries already present. Each program was constructed and examined on Ubuntu 24.04 underneath WSL2 with GCC and Clang, and on Home windows 11 with MSVC, Java, Python and .NET. All 5 languages print the identical demo output byte for byte, and each output block beneath comes from an actual run.
What Is a Binary Search Tree?
A binary search tree is a binary tree with an ordering rule: each key in a node’s left subtree is smaller than the node’s key, and each key in its proper subtree is bigger. The rule turns every comparability right into a step down the tree, so search, insert and delete value O(peak), which is O(log n) solely when the tree is balanced.
The ordering rule is the entire construction. A search compares the goal with the basis and goes left or proper, then repeats on the baby. The trail ends on the key or at an empty baby, which proves the secret is absent. The identical rule makes the in-order traversal print the keys in ascending order, a truth the ordered operations depend on. The Binary Timber article covers the node structure, the 4 traversals and why a recursive stroll overflows the decision stack on a deep tree, so this text doesn’t repeat them.
The ordered operations are the explanation to maintain the tree as an alternative of a hash desk. min and max stroll to the leftmost and rightmost node. The successor of a secret’s the following key in sorted order. It’s the leftmost node of the important thing’s proper subtree or, when that subtree is empty, the bottom ancestor whose left subtree holds the important thing. The predecessor mirrors it.
The ground of a secret’s the most important saved key not better than it, and the ceiling is the smallest saved key not lower than it. Rank asks what number of keys are smaller, and choose returns the k-th smallest. Rank and choose are the 2 operations that want the additional area this implementation shops in each node: the scale of the subtree rooted there.
A search tree is simply pretty much as good as its form. The textbook O(log n) is a median over random insertion orders. Insert sorted keys and each new node goes to the best of the earlier one, so the peak turns into n – 1 and each operation turns into a linear scan with additional pointers. Balanced variants corresponding to AVL and red-black bushes preserve the peak logarithmic for each order and pay for it with rotations on insert and delete.
This text retains the plain tree, measures the degeneration it can’t stop, and reveals what the ordered containers value by comparability. The C++, Java and C# libraries ship red-black bushes: std::set and std::map, TreeSet and TreeMap, and SortedSet<T> and SortedDictionary<TKey,TValue>. Python’s commonplace library has no balanced tree, and bisect over a sorted listing is the same old substitute. The B-tree article covers the on-disk ordered construction that databases use when the index doesn’t slot in reminiscence.
How This Was Measured
| Setting | Worth |
|---|---|
| Date examined | November 30, 2026 |
| {Hardware} | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Home windows 11 Schooling construct 26300 |
| Working system | Ubuntu 24.04.5 underneath WSL2, kernel 5.15.146, glibc 2.39; Home windows 11 for the MSVC, Java and .NET builds |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 and -O3 by CMake Launch; MSVC 19.44 at /W4 /WX |
| Language runtimes | OpenJDK 27.0.1.1 (the CI matrix covers 17, 21 and 25); CPython 3.14.6; .NET SDK 10.0.404 |
| Form experiment | 100,000 distinct keys: one shuffled permutation of 0 to 99,999 from a set xorshift64 seed, and the identical keys in ascending order |
| Delete experiment | The random 100,000-key tree, each key deleted in a deterministic random order, categorized by delete case earlier than removing |
| Ordered-operations experiment | The random 100,000-key tree, 100,000 deterministic queries per operation, comparisons counted |
| Normal-library benchmark | 100,000 random inserts plus lookups, then 10,000 sorted inserts plus lookups, customized tree in opposition to std::set, median of 5 runs |
| What’s timed | The comparisons and the insert, delete and lookup calls; key era and tree destruction are outdoors the timed areas |
| Statistic | Heights and imply depths in edges; averages for comparability counts; median of 5 runs for timings, in milliseconds |
| Examine | Each timing program prints a checksum of the values it learn, and the benchmark’s two buildings should agree on it |
No CPU pinning or frequency scaling management was used, and the host runs different software program, so the timings are indicative for this machine and the ratios are the helpful half. All heights, comparability counts and timings come from one machine and one WSL2 occasion. The form experiment’s sorted insertion is quadratic by development, about 5e9 comparisons for 100,000 keys, so it’s one run quite than a repeated median. The sorted tree is 99,999 ranges deep, which is why its peak and imply depth are computed with an specific stack quite than recursion.
The Ordered Operations and Their Price
| Operation | What it returns | Time |
|---|---|---|
| comprises | Whether or not the secret is saved | O(h) |
| insert | Provides a key if absent; duplicates are ignored | O(h) |
| delete | Removes a key by the leaf, one-child or two-child case | O(h) |
| min / max | Smallest and largest saved key | O(h) |
| successor / predecessor | Subsequent bigger and subsequent smaller saved key | O(h) |
| ground / ceiling | Largest key not better, smallest key not much less | O(h) |
| rank | Variety of saved keys strictly lower than the given key | O(h) with subtree sizes |
| choose | The important thing with precisely okay saved keys smaller than it (rank-indexed: choose(0) is the minimal, choose(dimension – 1) the utmost) | O(h) with subtree sizes |
| in-order | Each key in ascending order | O(n) |
h is the peak of the tree. For a balanced tree h is about log2 n, so one million keys want about 20 ranges. For the degenerate sorted tree it’s n – 1. The operations above by no means want multiple root-to-leaf path, and that’s the promise the plain binary search tree breaks when the enter arrives so as.
Binary Search Tree Implementation in C
C has no ordered container in its commonplace library, so the tree beneath is a whole implementation. Each node shops an int key, two baby pointers and the scale of its subtree. The tree construction holds solely the basis pointer, and the important thing depend is the basis’s subtree dimension. Absence is reported by bool out-parameters, so a saved worth can by no means be confused with a lacking reply, and the important thing sort is int as a result of C has no generics.
Search, Insert and the Ordered Stroll
bool bst_insert(Bst *tree, int key)
{
BstNode *recent = malloc(sizeof *recent);
BstNode **hyperlink = &tree->root;
BstNode *node = NULL;
if (recent == NULL)
return false;
whereas (*hyperlink != NULL) {
if (key == (*hyperlink)->key) {
free(recent);
return false;
}
hyperlink = key < (*hyperlink)->key ? &(*hyperlink)->left : &(*hyperlink)->proper;
}
fresh->key = key;
fresh->left = NULL;
fresh->proper = NULL;
fresh->dimension = 1;
*hyperlink = recent;
/* Each node above the brand new leaf gained one key. Stroll the identical path once more
* so no array of guardian hyperlinks is required. */
for (node = tree->root; node != recent; ) {
node->dimension++;
node = key < node->key ? node->left : node->proper;
}
return true;
}
bool bst_contains(const Bst *tree, int key)
{
const BstNode *node = tree->root;
whereas (node != NULL) {
if (key < node->key)
node = node->left;
else if (key > node->key)
node = node->proper;
else
return true;
}
return false;
}
/* The variety of saved keys strictly lower than key. */
size_t bst_rank(const Bst *tree, int key)
{
const BstNode *node = tree->root;
size_t rank = 0;
whereas (node != NULL) {
if (key <= node->key) {
node = node->left;
} else {
rank += node_size(node->left) + 1;
node = node->proper;
}
}
return rank;
}
/* The important thing with precisely okay saved keys smaller than it: choose(0) is the
* minimal, choose(dimension - 1) is the utmost, and rank(choose(okay)) is okay. Returns
* false when okay is outdoors 0 to dimension - 1. */
bool bst_select(const Bst *tree, size_t okay, int *out)
{
const BstNode *node = tree->root;
if (okay >= bst_size(tree))
return false;
whereas (node != NULL) {
size_t left = node_size(node->left);
if (okay < left) {
node = node->left;
} else if (okay == left) {
*out = node->key;
return true;
} else {
okay -= left + 1;
node = node->proper;
}
}
return false;
}
The search is the ordering rule in code: examine, go left when the secret is smaller, proper when it’s bigger, and cease at an empty pointer to show absence. Insert repeats the stroll and attaches a brand new leaf, and a replica secret’s discovered on the way in which and adjustments nothing.
As a result of each node is aware of its subtree dimension, rank is identical stroll with a working depend. It provides the left subtree’s dimension plus one at any time when the secret is bigger than the node, goes left in any other case, and runs right down to an empty pointer. Choose walks the sizes as an alternative of the keys, going left when okay is beneath the left subtree’s dimension, proper when it’s above, and returning the node when the rest is zero. Min and max are the ends of that stroll, and successor and predecessor every have a right-subtree case and an ancestor case.
Erasing a Node
bool bst_erase(Bst *tree, int key)
{
BstNode **hyperlink = &tree->root;
BstNode *node = NULL;
BstNode **succ_link = NULL;
BstNode *succ = NULL;
BstNode **step = NULL;
whereas (*hyperlink != NULL && (*hyperlink)->key != key)
hyperlink = key < (*hyperlink)->key ? &(*hyperlink)->left : &(*hyperlink)->proper;
node = *hyperlink;
if (node == NULL)
return false;
if (node->left == NULL || node->proper == NULL) {
BstNode *baby = node->left != NULL ? node->left : node->proper;
lose_one_on_path(tree, key, hyperlink);
*hyperlink = baby;
free(node);
return true;
}
succ_link = &node->proper;
whereas ((*succ_link)->left != NULL)
succ_link = &(*succ_link)->left;
succ = *succ_link;
lose_one_on_path(tree, key, hyperlink);
node->size--;
for (step = &node->proper; step != succ_link; step = &(*step)->left)
(*step)->size--;
*succ_link = succ->proper;
node->key = succ->key;
free(succ);
return true;
}
The delete operate walks with a pointer to the hyperlink that holds the present node, so eradicating the basis wants no particular case: writing by hyperlink replaces no matter pointed on the node. A leaf is freed and its hyperlink turns into NULL, and a node with one baby is changed by that baby. A node with two kids takes the important thing of its in-order successor, and the successor, which has no left baby, is unlinked from the best subtree and freed.
Earlier than any pointer adjustments, lose_one_on_path walks from the basis to the eliminated place and decrements each subtree dimension on the way in which. The 2-child case additionally decrements the sizes on the trail right down to the successor. That retains rank and choose appropriate after each delete.
The tree is freed with an specific loop that rotates every left baby up earlier than transferring down, so a 100,000-level sorted tree is launched with out recursing. The exams free a 100,000-node random tree and a ten,000-key sorted chain, and the sanitizer job runs them underneath LeakSanitizer.
The C Demo
The demo builds the tree that Determine 1 makes use of, then workout routines one operation at a time: the ordered queries first, then the three delete circumstances, then a replica insert that should go away the scale unchanged.
Output:
binary search tree, ordered operations
insert 50, 30, 70, 20, 40, 60, 80, 25 -> dimension 8, peak 3
min 20, max 80
comprises 40 -> true, comprises 45 -> false
ground 45 -> 40, ceiling 45 -> 50
rank 40 -> 3, choose 3 -> 40
in-order: 20 25 30 40 50 60 70 80
successor 40 -> 50, predecessor 40 -> 30
delete 20 (one baby) -> dimension 7, in-order: 25 30 40 50 60 70 80
delete 25 (leaf) -> dimension 6, in-order: 30 40 50 60 70 80
delete 50 (two kids) -> dimension 5, in-order: 30 40 60 70 80
insert 60 -> dimension 5
Binary Search Tree Implementation in C++
In C++ the identical design turns into a category template over the important thing sort and a comparator, with std::non-compulsory for absence and std::unique_ptr for the nodes. The ordered API is full: insert, comprises, erase, min, max, successor, predecessor, ground, ceiling, rank, choose, peak, dimension and in-order.
bool insert(Ok key)
{
std::unique_ptr<Node>* hyperlink = &root_;
whereas (*hyperlink) {
if (comp_(key, (*hyperlink)->key))
hyperlink = &(*hyperlink)->left;
else if (comp_((*hyperlink)->key, key))
hyperlink = &(*hyperlink)->proper;
else
return false; // neither key compares earlier than the opposite
}
*hyperlink = std::make_unique<Node>(std::transfer(key));
Node* inserted = link->get();
// The ancestors are nonetheless above the brand new node: depend it in every of them.
Node* ancestor = root_.get();
whereas (ancestor != inserted) {
++ancestor->subtree_size;
ancestor = comp_(inserted->key, ancestor->key) ? ancestor->left.get()
: ancestor->proper.get();
}
++size_;
return true;
}
bool erase(const Ok& key)
{
std::vector<Node*> ancestors;
std::unique_ptr<Node>* hyperlink = &root_;
whereas (*hyperlink) {
if (comp_(key, (*hyperlink)->key)) {
ancestors.push_back(link->get());
hyperlink = &(*hyperlink)->left;
} else if (comp_((*hyperlink)->key, key)) {
ancestors.push_back(link->get());
hyperlink = &(*hyperlink)->proper;
} else {
break;
}
}
if (!*hyperlink)
return false; // the secret is not within the tree
for (Node* ancestor : ancestors)
--ancestor->subtree_size;
Node* node = link->get();
if (!node->left || !node->proper) {
// A leaf, or one baby: the kid, if any, takes the node's place.
// Transfer the kid out first; assigning over the node frees it.
std::unique_ptr<Node> baby =
std::transfer(node->left ? node->left : node->proper);
*hyperlink = std::transfer(baby);
} else {
// Two kids: copy the in-order successor's key into the node and
// unlink the successor, which has no left baby.
std::unique_ptr<Node>* successor_link = &node->proper;
std::vector<Node*> successor_ancestors;
whereas ((*successor_link)->left) {
successor_ancestors.push_back(successor_link->get());
successor_link = &(*successor_link)->left;
}
Node* successor = successor_link->get();
node->key = std::transfer(successor->key);
--node->subtree_size;
for (Node* ancestor : successor_ancestors)
--ancestor->subtree_size;
std::unique_ptr<Node> proper = std::transfer(successor->proper);
*successor_link = std::transfer(proper);
}
--size_;
return true;
}
// Variety of keys strictly lower than key. O(peak): every step provides the
// complete left subtree of a node that compares earlier than the important thing.
[[nodiscard]] size_type rank(const Ok& key) const
{
size_type much less = 0;
const Node* node = root_.get();
whereas (node != nullptr) {
if (comp_(node->key, key)) {
much less += node_size(node->left.get()) + 1;
node = node->proper.get();
} else {
node = node->left.get();
}
}
return much less;
}
// The important thing with precisely okay saved keys smaller than it: choose(0) is the
// minimal and choose(dimension - 1) is the utmost, so rank(choose(okay)) == okay.
// Absent when okay is outdoors 0 to dimension - 1.
[[nodiscard]] std::non-compulsory<Ok> choose(size_type okay) const
{
if (okay >= size_)
return std::nullopt;
const Node* node = root_.get();
whereas (node != nullptr) {
const size_type left = node_size(node->left.get());
if (okay < left) {
node = node->left.get();
} else if (okay == left) {
return std::non-compulsory<Ok>(node->key);
} else {
okay -= left + 1;
node = node->proper.get();
}
}
return std::nullopt; // unreachable whereas the sizes are appropriate
}
Two particulars differ from the C model. The comparator is a template parameter defaulting to std::much less<Ok>, so the tree orders any sort with a strict weak ordering, together with std::string. And absence is an empty std::non-compulsory, so the worth sort doesn’t want a sentinel, whereas rank nonetheless returns a plain std::size_t.
std::set, the Balanced Different
For manufacturing C++, use std::set or std::map from <set> and <map>. They’re ordered containers applied as red-black bushes: insert, erase, discover, lower_bound, upper_bound and the ordered iteration all value O(log n) for each insertion order, not solely random ones. lower_bound returns the ceiling (the primary key not lower than the argument), upper_bound returns the strict successor, and std::prev of upper_bound offers the ground. The worth is a continuing issue that the benchmark measures, and the profit is that the logarithm can’t be misplaced to a foul enter order. The STL containers information covers the remainder of that container household.
The comparability the containers can’t do as instantly is rank and choose. std::set has no order-statistics operations, so a program that wants them both shops subtree sizes in its personal tree, as this text does, or pays O(n) to stroll to the k-th factor. That’s the one case the place the hand-written ordered tree earns its complexity.
The C++ Demo
The C++ demo prints precisely the identical bytes because the C program, and the construct compares it in opposition to the identical anticipated file. The std::set benchmark later within the article makes use of the identical 100,000 random keys and the sorted case that breaks the plain tree.
Binary Search Tree Implementation in Java, Python and C#
The three variations comply with the C design with generic keys: a subtree dimension per node, iterative walks, and absence reported by the language’s idiomatic empty end result. Their commonplace libraries differ in what they supply. Java has TreeSet and TreeMap, red-black bushes with the total ordered API besides rank and choose. C# has SortedSet<T> and SortedDictionary<TKey,TValue>, additionally red-black bushes. Python’s commonplace library has no balanced tree in any respect. bisect over a sorted listing offers binary search and insertion by index, and a third-party bundle is required for an ordered map.
Java
public boolean put(E key) {
Objects.requireNonNull(key, "null values usually are not supported: null studies absence");
if (root == null) {
root = new Node<>(key);
return true;
}
Listing<Node<E>> path = new ArrayList<>();
Node<E> node = root;
whereas (true) {
int examine = key.compareTo(node.key);
if (examine == 0) {
return false;
}
path.add(node);
Node<E> subsequent = examine < 0 ? node.left : node.proper;
if (subsequent == null) {
if (examine < 0) {
node.left = new Node<>(key);
} else {
node.proper = new Node<>(key);
}
for (Node<E> ancestor : path) {
ancestor.dimension++; // the brand new key joins each subtree on the trail
}
return true;
}
node = subsequent;
}
}
public boolean take away(E key) {
Objects.requireNonNull(key, "null values usually are not supported: null studies absence");
Listing<Node<E>> path = new ArrayList<>();
Node<E> node = root;
whereas (node != null) {
int examine = key.compareTo(node.key);
if (examine == 0) {
break;
}
path.add(node);
node = examine < 0 ? node.left : node.proper;
}
if (node == null) {
return false;
}
if (node.left != null && node.proper != null) {
// Two kids: copy the successor's key in, then unlink the successor,
// which has no left baby. This retains the in-order sequence and the
// subtree sizes round it appropriate.
Node<E> successor = node.proper;
Listing<Node<E>> descent = new ArrayList<>();
whereas (successor.left != null) {
descent.add(successor);
successor = successor.left;
}
node.key = successor.key;
if (descent.isEmpty()) {
node.proper = successor.proper;
} else {
descent.get(descent.dimension() - 1).left = successor.proper;
}
for (Node<E> ancestor : path) {
ancestor.size--;
}
for (Node<E> beneath : descent) {
beneath.size--;
}
node.size--;
} else {
// Zero or one baby: change the node with its solely baby, or with null.
Node<E> baby = node.left != null ? node.left : node.proper;
if (path.isEmpty()) {
root = baby;
} else {
Node<E> guardian = path.get(path.dimension() - 1);
if (guardian.left == node) {
guardian.left = baby;
} else {
guardian.proper = baby;
}
}
for (Node<E> ancestor : path) {
ancestor.size--;
}
}
return true;
}
The category is generic over E extends Comparable<E>, so the ordering comes from compareTo and the tree wants no comparator parameter. Absence is null, and the category rejects null keys for that motive. rank and choose use the saved subtree sizes, and choose is rank-indexed, so rank and choose are precise inverses. The exams examine it in opposition to a sorted ArrayList mannequin.
In software code, TreeSet and TreeMap give the identical ordered operations with a red-black tree beneath. ground, ceiling, decrease, larger, first and final are the tactic names to search for, and subSet returns a spread view. Neither gives rank or choose, for a similar motive as C++.
Python
def _insert(root: _Node[K] | None, key: Ok) -> tuple[_Node[K], bool]:
"""Insert a key underneath root, returning the brand new root and whether or not it was new.
The stroll is a loop, so sorted enter that builds a series as deep because the tree
is giant can't hit Python's recursion restrict.
"""
if root is None:
return _Node(key), True
path: listing[_Node[K]] = []
node = root
whereas True:
path.append(node)
if key < node.key:
if node.left is None:
node.left = _Node(key)
break
node = node.left
elif node.key < key:
if node.proper is None:
node.proper = _Node(key)
break
node = node.proper
else:
return root, False
for ancestor in path:
ancestor.dimension += 1
return root, True
def _erase(root: _Node[K] | None, key: Ok) -> tuple[_Node[K] | None, bool]:
"""Erase a key underneath root, returning the brand new root and whether or not it was there.
The leaf and one-child circumstances unlink the node. The 2-child case copies the
in-order successor's key into the node after which unlinks the successor, which
has no left baby, so the tree retains the identical in-order sequence.
"""
path: listing[_Node[K]] = []
node = root
whereas node will not be None:
if key < node.key:
path.append(node)
node = node.left
elif node.key < key:
path.append(node)
node = node.proper
else:
break
if node is None:
return root, False
for ancestor in path:
ancestor.dimension -= 1
if node.left will not be None and node.proper will not be None:
node.dimension -= 1
guardian = node
successor = node.proper
whereas successor.left will not be None:
successor.dimension -= 1
guardian = successor
successor = successor.left
node.key = successor.key
if guardian is node:
guardian.proper = successor.proper
else:
guardian.left = successor.proper
return root, True
baby = node.left if node.left will not be None else node.proper
if not path:
return baby, True
guardian = path[-1]
if guardian.left is node:
guardian.left = baby
else:
guardian.proper = baby
return root, True
def rank(self, key: Ok) -> int:
"""Return the variety of keys strictly lower than key."""
depend = 0
node = self._root
whereas node will not be None:
if key < node.key:
node = node.left
elif node.key < key:
depend += _size(node.left) + 1
node = node.proper
else:
return depend + _size(node.left)
return depend
def choose(self, okay: int) -> Ok | None:
"""Return the important thing whose rank is okay, or None when okay is outdoors 0 to dimension - 1.
The rank is the variety of saved keys strictly lower than the important thing, so
choose(0) is the minimal and rank(choose(okay)) is okay.
"""
node = self._root
whereas node will not be None:
left = _size(node.left)
if okay < left:
node = node.left
elif okay == left:
return node.key
else:
okay -= left + 1
node = node.proper
return None
The ordering comes from the important thing sort’s < operator, and absence is None, so insert(None) raises TypeError. Each stroll is a loop, together with the peak and the in-order traversal, as a result of a recursive model stops with RecursionError as soon as sorted enter builds a series deeper than the default restrict of 1,000 frames. The exams construct and empty a 5,000-key sorted chain to show it, and examine all the pieces else in opposition to a bisect-maintained sorted listing.
For software code, Python’s commonplace library gives bisect over a sorted listing: binary search, the insertion level (which is the ground or ceiling place), and O(n) insertion as a result of the listing shifts. For an ordered map that wants the tree’s asymptotics, third-party packages corresponding to sortedcontainers are the same old reply. The built-in dict retains insertion order, not key order, so it can’t reply the ordered questions.
C#
public bool Insert(TKey key)
{
ArgumentNullException.ThrowIfNull(key);
if (_root is null)
{
_root = new Node(key);
return true;
}
// Nodes on the search path: every of them positive aspects one key in its subtree.
var path = new Listing<Node>();
Node node = _root;
whereas (true)
{
int order = key.CompareTo(node.Key);
if (order == 0)
return false;
path.Add(node);
if (order < 0)
{
if (node.Left is null)
{
node.Left = new Node(key);
break;
}
node = node.Left;
}
else
{
if (node.Proper is null)
{
node.Proper = new Node(key);
break;
}
node = node.Proper;
}
}
foreach (Node ancestor in path)
ancestor.Measurement++;
return true;
}
public bool Take away(TKey key)
{
ArgumentNullException.ThrowIfNull(key);
// Ancestors of the node that's truly unlinked, root first. Each
// considered one of them loses one key from its subtree dimension.
var ancestors = new Listing<Node>();
Node? node = _root;
whereas (node will not be null)
{
int order = key.CompareTo(node.Key);
if (order == 0)
break;
ancestors.Add(node);
node = order < 0 ? node.Left : node.Proper;
}
if (node is null)
return false;
if (node.Left will not be null && node.Proper will not be null)
{
// Two kids: transfer to the in-order successor, the leftmost node
// of the best subtree, then unlink the successor. It has no left
// baby, so unlinking it's the straightforward case.
Node successorParent = node;
Node successor = node.Proper;
node.Measurement--;
whereas (successor.Left will not be null)
{
successorParent = successor;
successorParent.Measurement--;
successor = successor.Left;
}
node.Key = successor.Key;
Node? baby = successor.Proper;
if (successorParent == node)
successorParent.Proper = baby;
else
successorParent.Left = baby;
}
else
{
Node? baby = node.Left ?? node.Proper;
if (ancestors.Rely == 0)
_root = baby;
else if (ancestors[^1].Left == node)
ancestors[^1].Left = baby;
else
ancestors[^1].Proper = baby;
}
foreach (Node ancestor in ancestors)
ancestor.Measurement--;
return true;
}
The C# class is generic over TKey with an IComparable<TKey> constraint, makes use of a Attempt...-style out end result for absence, and retains the identical subtree-size augmentation. The exams examine it in opposition to SortedSet<TKey> and a sorted-list mannequin, and examine the rank and choose boundaries.
In software code, SortedSet<T> and SortedDictionary<TKey,TValue> are the red-black-tree containers. GetViewBetween returns a spread view, Min and Max are properties, and there’s no rank or choose. They’re the closest library equivalents to the tree constructed right here.
Top on Random and Sorted Enter
The form experiment inserts the identical 100,000 keys twice: as soon as as a shuffled permutation, as soon as in ascending order. It studies the peak, the imply depth, the construct time and the common comparisons for 10,000 lookups. The sorted tree reaches 99,999 ranges, so each measurement in this system makes use of an specific loop quite than recursion. The Binary Timber article measures the place the recursive stroll overflows as an alternative.
static bool tree_stats(const Node *root, int *peak, double *mean_depth)
{
NodeVec degree = { NULL, 0, 0 };
NodeVec subsequent = { NULL, 0, 0 };
unsigned lengthy lengthy total_depth = 0;
size_t depend = 0;
int depth = -1;
bool okay = true;
if (root != NULL)
okay = vec_push(°ree, root);
whereas (okay && degree.len > 0) {
size_t i;
depth++;
total_depth += (unsigned lengthy lengthy)depth *
(unsigned lengthy lengthy)degree.len;
depend += degree.len;
subsequent.len = 0;
for (i = 0; i < degree.len; ++i) {
if (degree.gadgets[i]->left != NULL)
okay = vec_push(&subsequent, degree.gadgets[i]->left);
if (okay && degree.gadgets[i]->proper != NULL)
okay = vec_push(&subsequent, degree.gadgets[i]->proper);
}
{
NodeVec swap = degree;
degree = subsequent;
subsequent = swap;
}
}
free(degree.gadgets);
free(subsequent.gadgets);
if (!okay)
return false;
*peak = depth;
*mean_depth = depend == 0 ? 0.0 : (double)total_depth / (double)depend;
return true;
}
Output:
100,000 keys, peak and imply depth in edges
construct order peak mean_depth build_ms lookup_comparisons
random 40 19.92 18 20.94
sorted 99999 49999.50 14606 49948.02
random tree, deleting keys
after 25000 deletions: dimension 75000 peak 39
after 50000 deletions: dimension 50000 peak 36
after 75000 deletions: dimension 25000 peak 33
The random 100,000-key tree got here out 40 ranges excessive with a imply depth of 19.92 edges, and the sorted tree 99,999 ranges excessive with a imply depth of 49,999.50. The textbook expectation for a random tree is a imply depth close to 2H_n – 4, about 20.2 for this n, and the measured 19.92 agrees to inside 1.5%. The asymptotic system for the anticipated peak, 4.311 ln n – 1.953 ln ln n, offers about 45, however it converges slowly and overstates the peak at this dimension. The imply depth, whose precise expectation is understood, is the sharper examine.
The construct time separates the 2 orders extra sharply than any depend: 18 ms for the shuffled keys in opposition to 14,606 ms for the ascending ones, about 800 occasions longer for a similar inserts, as a result of the ascending construct makes roughly 5e9 comparisons. The sampled lookups inform the identical story, 20.94 comparisons on the random tree in opposition to 49,948 on the sorted one. Deleting 1 / 4, half and three quarters of the keys shrank the random tree from peak 40 to 39, 36 and 33, so deletion prunes the tree with out rebalancing it.
Deleting a Node: Leaf, One Baby, Two Kids
Deletion is the operation that separates a tree that works on paper from one which passes a mannequin check. A leaf disappears. A node with one baby is changed by that baby. A node with two kids can’t merely be eliminated, as a result of each subtrees have to remain. The usual transfer finds the in-order successor, the smallest key in the best subtree, copies its key over the node’s key, after which deletes that successor, which has no left baby.
The demo output within the C part reveals the three circumstances so as: 20 has one baby (25), 25 is a leaf by the point it’s deleted, and 50 has two kids, so the successor 60 takes its place. The in-order row after every delete is what proves the ordering survived.
The delete experiment runs the three circumstances at scale on the random 100,000-key tree and counts the comparisons every delete spends discovering its key, grouped by the case the node was in earlier than removing:
static int erase_classified(Node **root, int key,
unsigned lengthy lengthy *comparisons)
{
Node **hyperlink = root;
Node *node;
int which;
whereas (*hyperlink != NULL) {
(*comparisons)++;
if (key < (*hyperlink)->key)
hyperlink = &(*hyperlink)->left;
else if (key > (*hyperlink)->key)
hyperlink = &(*hyperlink)->proper;
else
break;
}
node = *hyperlink;
if (node == NULL)
return CASE_COUNT;
if (node->left == NULL && node->proper == NULL)
which = CASE_LEAF;
else if (node->left != NULL && node->proper != NULL)
which = CASE_TWO;
else
which = CASE_ONE;
if (node->left != NULL && node->proper != NULL) {
Node **succ_link = &node->proper;
Node *succ;
whereas ((*succ_link)->left != NULL)
succ_link = &(*succ_link)->left;
succ = *succ_link;
*succ_link = succ->proper;
node->key = succ->key;
node = succ;
} else if (node->left != NULL) {
*hyperlink = node->left;
} else {
*hyperlink = node->proper;
}
free(node);
return which;
}
Output:
random tree, 100,000 keys, deletion in random order
case deletions avg_comparisons
leaf 34035 20.13
one baby 32257 19.22
two kids 33708 17.22
ultimate dimension 0, empty true
The random deletion order put 34,035 leaves, 32,257 one-child nodes and 33,708 two-child nodes by the three circumstances. The typical comparisons are shut: 20.13 for a leaf, 19.22 for a one-child node and 17.22 for a two-child node. The 2-child case is the most cost effective right here, not as a result of copying the successor is free, however as a result of a node with two kids can’t sit on the backside of the tree: it’s above the leaves, so the search reaches it in fewer comparisons. The costly a part of deletion is the peak of the tree the search has to stroll, and the case distribution barely adjustments that stroll.
What the Ordered Operations Price
The operations that justify a search tree over a hash desk are the ordered ones. The experiment runs 100,000 deterministic queries per operation on the identical random 100,000-key tree and counts comparisons:
static size_t tree_rank(const Node *node, int key,
unsigned lengthy lengthy *comparisons)
{
size_t rank = 0;
whereas (node != NULL) {
(*comparisons)++;
if (key <= node->key) {
node = node->left;
} else {
rank += node_size(node->left) + 1;
node = node->proper;
}
}
return rank;
}
/* choose compares no keys: it follows the subtree sizes. */
static bool tree_select(const Node *node, size_t okay, int *out)
{
if (okay >= node_size(node))
return false;
whereas (node != NULL) {
size_t left = node_size(node->left);
if (okay < left) {
node = node->left;
} else if (okay == left) {
*out = node->key;
return true;
} else {
okay -= left + 1;
node = node->proper;
}
}
return false;
}
Output:
100,000-key random tree
operation queries avg_comparisons
comprises 100000 20.92
min 100000 0.00
max 100000 0.00
successor 100000 21.93
predecessor 100000 21.92
ground 100000 21.93
ceiling 100000 21.92
rank 100000 21.92
choose 100000 0.00
Each key-based operation averaged about 21 comparisons on this tree, from 20.92 for comprises to 21.93 for successor, ground and ceiling, near the 19.92 imply depth of the tree. Every operation walks one root-to-leaf path and compares as soon as per node.
The three zeros are the operations that don’t examine keys in any respect. min and max comply with baby pointers solely, and choose compares the requested rank with subtree sizes, so none of them performs a key comparability. Rank will not be in that group, as a result of it compares the important thing at each node on its path, and its 21.92 is that stroll. The sensible studying is that the augmented tree makes rank no costlier than comprises: the identical path, plus a couple of additions.
Customized Tree Towards std::set
The usual library’s ordered container is a balanced tree, and the benchmark compares the hand-written tree with it. The random case reveals the fixed issue of two implementations of the identical thought, and the sorted case reveals the worth of not balancing.
int fundamental()
{
const std::vector<int> random_keys = shuffled_keys(kRandomKeys);
const std::vector<int> sorted_keys = ascending_keys(kSortedKeys);
const Consequence custom_random = median_run([&random_keys] {
return run_custom_once(random_keys);
});
const Consequence std_random = median_run([&random_keys] {
return run_std_once(random_keys);
});
const Consequence custom_sorted = median_run([&sorted_keys] {
return run_custom_once(sorted_keys);
});
const Consequence std_sorted = median_run([&sorted_keys] {
return run_std_once(sorted_keys);
});
if (custom_random.checksum != std_random.checksum ||
custom_sorted.checksum != std_sorted.checksum) {
std::fprintf(stderr, "checksum mismatch between the containersn");
return EXIT_FAILURE;
}
const std::uint64_t checksum =
fold_checksums(custom_random.checksum, custom_sorted.checksum);
std::printf("100,000 random inserts + lookups, median of 5 runs (ms)n");
std::printf("customized BST %.1fn", custom_random.ms);
std::printf("std::set %.1fn", std_random.ms);
std::printf("10,000 sorted inserts + lookups, median of 5 runs (ms)n");
std::printf("customized BST %.1fn", custom_sorted.ms);
std::printf("std::set %.1fn", std_sorted.ms);
std::printf("checksum: %llun",
static_cast<unsigned lengthy lengthy>(checksum));
return EXIT_SUCCESS;
}
Output:
100,000 random inserts + lookups, median of 5 runs (ms)
customized BST 67.1
std::set 34.3
10,000 sorted inserts + lookups, median of 5 runs (ms)
customized BST 1860.1
std::set 1.1
checksum: 4630652801823639509
On random enter, 100,000 inserts and lookups took 67.1 ms within the customized tree and 34.3 ms in std::set: the red-black tree was about twice as quick for a similar asymptotics, probably as a result of the customized insert walks the trail a second time to replace subtree sizes and the random tree is taller than a red-black tree of the identical keys. On 10,000 sorted inserts and lookups the hole turns into the entire level: 1,860.1 ms for the customized tree in opposition to 1.1 ms for std::set, about 1,700 occasions slower, as a result of the sorted customized tree is an inventory of 9,999 ranges whereas the red-black tree stays logarithmic no matter insertion order.
The customized tree’s benefit will not be velocity. It’s the rank and choose operations the library doesn’t expose, and the benchmark reveals what that management prices on this machine.
5 Methods a Binary Search Tree Passes a Fast Check and Nonetheless Fails
Every of those applications compiles cleanly with -Wall -Wextra -pedantic and prints one thing believable till the road beneath it. The primary 4 stay within the C repository’s pitfalls/ listing and the fifth within the C++ repository’s; the workflows re-run every and assert the road or sanitizer abstract that reveals the bug.
1. A Successor With out the Ancestor Case
static bool successor_buggy(const Node *root, int key, int *out)
node->proper == NULL)
return false;
node = node->proper;
whereas (node->left != NULL)
node = node->left;
*out = node->key;
return true;
Output:
successor_no_ancestor: a successor that solely seems proper
successor 30 -> 40, anticipated 40
successor 60 -> none, anticipated 70
The buggy successor solely is aware of the right-subtree case. For 30 it returns 40 accurately, as a result of 40 is the leftmost node of 30’s proper subtree. For 60, whose proper subtree is empty, it returns none, however the reply is the ancestor 70. The repair is the second half of the algorithm: stroll down from the basis, remembering the final ancestor from which the search turned left.
2. Flooring and Ceiling on the Improper Facet
static bool floor_buggy(const Node *root, int key, int *out)
{
const Node *node = root;
const Node *finest = NULL;
whereas (node != NULL) {
if (node->key >= key) {
finest = node;
node = node->left;
} else {
node = node->proper;
}
}
if (finest == NULL)
return false;
*out = best->key;
return true;
}
/* The bug: the mirror picture, so this returns the ground. */
static bool ceiling_buggy(const Node *root, int key, int *out)
{
const Node *node = root;
const Node *finest = NULL;
whereas (node != NULL) {
if (node->key <= key) {
finest = node;
node = node->proper;
} else {
node = node->left;
}
}
if (finest == NULL)
return false;
*out = best->key;
return true;
}
Output:
floor_ceiling_swapped: ground and ceiling with the comparability reversed
ground 45 -> 50, anticipated 40
ceiling 45 -> 40, anticipated 50
Reversing the comparability turns ground into ceiling and ceiling into ground: ground(45) returns 50 and ceiling(45) returns 40. The features look believable in isolation and fail just for keys that aren’t saved. They’re the identical stroll with the candidate replace on the proper facet, which is the repair.
3. A Two-Baby Delete That Leaks the Successor
static bool erase_buggy(Node **root, int key)
{
Node **hyperlink = root;
Node *node;
whereas (*hyperlink != NULL && (*hyperlink)->key != key)
hyperlink = key < (*hyperlink)->key ? &(*hyperlink)->left : &(*hyperlink)->proper;
node = *hyperlink;
if (node == NULL)
return false;
if (node->left != NULL && node->proper != NULL) {
Node **succ_link = &node->proper;
Node *succ;
whereas ((*succ_link)->left != NULL)
succ_link = &(*succ_link)->left;
succ = *succ_link;
*succ_link = succ->proper;
node->key = succ->key;
return true; /* the successor node is rarely freed */
}
*hyperlink = node->left != NULL ? node->left : node->proper;
free(node);
return true;
}
Output:
delete_two_children_leak: the successor node is unlinked however not freed
in-order after delete 50: 20 30 40 60 70 80
Output (summarized from the LeakSanitizer report):
AddressSanitizer: LeakSanitizer detected a reminiscence leak
Direct leak of 24 byte(s) in 1 object(s)
allotted at delete_two_children_leak.c:30
The erase path relinks the successor’s baby and copies the successor’s key, however by no means frees the successor node. The in-order output is appropriate and the tree seems proper, whereas LeakSanitizer studies a direct leak of 24 bytes, one node. A two-child delete frees precisely one node, and the case is straightforward to overlook as a result of the seen output by no means reveals the leak.
4. Duplicate Keys By the Proper Department
static Node *insert_buggy(Node *root, int key)
{
Node **hyperlink = &root;
whereas (*hyperlink != NULL)
hyperlink = key < (*hyperlink)->key ? &(*hyperlink)->left : &(*hyperlink)->proper;
*hyperlink = malloc(sizeof **hyperlink);
if (*hyperlink == NULL) {
fputs("out of memoryn", stderr);
exit(EXIT_FAILURE);
}
(*hyperlink)->key = key;
(*hyperlink)->left = NULL;
(*hyperlink)->proper = NULL;
return root;
}
Output:
duplicate_keys: insert sends equal keys proper and by no means checks
insert 40 twice -> dimension 2, anticipated 1
in-order: 40 40
insert 60 -> dimension 3, anticipated 2
rank 60 -> 2, anticipated 1
Equality despatched to the best with out a examine shops 40 twice: dimension 2, an in-order row of 40 40, and rank 60 counts the duplicate and returns 2 as an alternative of 1. The repair is one comparability earlier than the stroll continues, as a result of each ordered operation depends on there being precisely one node per key.
5. A Reference Right into a std::set Throughout an Erase
// dangling_set_reference.cpp - DO NOT COPY. A reference to a std::set factor
// is legitimate solely whereas that factor stays within the set. erase() destroys the node,
// so the reference dangles and the learn is undefined behaviour; AddressSanitizer
// studies heap-use-after-free.
// Construct: g++ -std=c++17 -Wall -Wextra -pedantic -g -fsanitize=handle pitfalls/dangling_set_reference.cpp -o dangling_set_reference
#embody <iostream>
#embody <set>
int fundamental()
{
std::set<int> values{40, 50, 60};
const int& reference = *values.discover(50);
std::cout << "dangling_set_reference: reference into std::set throughout erasen";
std::cout << "earlier than erase: " << reference << 'n';
values.erase(values.discover(50));
std::cout << "dimension after erase: " << values.dimension() << 'n';
std::cout.flush();
// The node that held 50 was freed by erase(). Studying reference right here is
// the heap-use-after-free that AddressSanitizer studies.
std::cout << "stale worth: " << reference << 'n';
return 0;
}
Output:
AddressSanitizer: heap-use-after-free
READ of dimension 4 at pitfalls/dangling_set_reference.cpp:22
32 bytes inside a 40-byte area freed by std::set::erase at pitfalls/dangling_set_reference.cpp:16
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/dangling_set_reference.cpp:22 in fundamental
A reference right into a std::set is legitimate solely whereas its factor stays within the set. This system prints 50 earlier than the erase after which reads the identical reference after it, and AddressSanitizer studies a heap-use-after-free as a result of the node went again to the allocator. Copy the worth out earlier than erasing, or preserve an iterator and erase it solely when the worth is not wanted.
Key Takeaways
- The ordering rule turns comparisons right into a path, so each ordered operation prices O(peak). The tree retains its O(log n) promise solely whereas it stays balanced.
- Inserting 100,000 keys in sorted order produced a tree 99,999 ranges deep, in opposition to 40 for a similar keys shuffled, which is the distinction between a tree and an inventory.
- The subtree dimension in every node makes rank and choose one root-to-leaf stroll, and the 2 are precise inverses when choose is rank-indexed.
- The three delete circumstances are one algorithm as soon as the successor is outlined: a leaf is unlinked, a one-child node is changed, and a two-child node takes its successor’s key.
- A random 100,000-key tree offers each ordered operation a brief path, about 21 comparisons in opposition to a imply depth of 19.92.
std::setgained each benchmark circumstances on this machine, 34.3 ms in opposition to 67.1 ms on random enter and 1.1 ms in opposition to 1,860.1 ms on sorted enter. The hand-written tree’s worth is the rank and choose operations the library doesn’t expose, not uncooked velocity.- Successor, predecessor, ground and ceiling are the identical stroll with a special rule for remembering the candidate, and getting that rule improper is the bug behind pitfalls 1 and a couple of.
Continuously Requested Questions
Conclusion
The binary search tree is the construction the place the common case hides the entire story. Its operations are brief walks when the form is nice and linear scans when the enter arrives sorted, and the identical 40 in opposition to 99,999 ranges separate the 2 circumstances right here. The ordered operations, and the subtree sizes that make rank and choose low cost, are the half a hash desk can’t present. The degeneration is the half the balanced containers exist to forestall.
In manufacturing code, use the library’s balanced container until rank and choose or a customized traversal are required, and if the insertion order will not be underneath this system’s management, use it anyway. For a key lookup with no ordering, the hash desk is the quicker software. The kinds of knowledge buildings information reveals the place the search tree sits among the many others, and the knowledge buildings hub lists each article within the sequence.
Supply Code and Checks
All applications on this web page are within the data-structures/binary-search-tree listing of the 5 MYCPLUS instance repositories:
The C and C++ examples construct and check with CMake:
cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure
Java runs with javac --release 17 -Xlint:all -Werror -d construct src/*.java exams/*.java adopted by java -ea -cp construct BstTest. Python runs with python -m unittest uncover -s exams -v, and C# with dotnet construct BinarySearchTree.slnx -c Launch adopted by dotnet run --project exams/BstTests -c Launch --no-build.
What the builds examine. Each demo’s stdout is in contrast byte for byte with exams/anticipated/ordered.txt. The exams examine each operation in opposition to a sorted-array mannequin over not less than 100,000 random operations (200,000 in C), examine the subtree sizes in opposition to an impartial depend, cross-check rank and choose, and canopy the boundaries, an empty tree and a delete-and-reinsert churn. The C and C++ workflows additionally run the exams, demo and pitfalls underneath AddressSanitizer and UndefinedBehaviorSanitizer, and the C workflow checks the leak reported by the two-child delete pitfall. The builds don’t examine the peak, comparability or timing figures: these belong to 1 machine and are captured with the article.
What I Verified
The instance directories include the check applications and the captured runs, and the desk states which system ran every examine.
| Examine | Ubuntu 24.04 (WSL2) | Home windows 11 (MSVC) |
|---|---|---|
| Construct and exams, C, GCC 13.3 | Move (6 of 6 exams) | Not relevant |
| Construct and exams, C, Clang 18.1.3 | Move (6 of 6 exams) | Not relevant |
Construct and exams, C, MSVC 19.44 /W4 /WX |
Not relevant | Move (6 of 6 exams) |
| Construct and exams, C++, g++ 13.3 | Move (2 of two exams) | Not relevant |
| Construct and exams, C++, clang++ 18.1.3 | Move (2 of two exams) | Not relevant |
Construct and exams, C++, MSVC 19.44 /W4 /WX /permissive- |
Not relevant | Move (2 of two exams) |
| Java exams (JDK 21 on WSL, JDK 27 on Home windows) | Move (exams and the demo diff) | Move (exams and the demo diff) |
| Python exams (3.12.3 on WSL, 3.14.6 on Home windows), ruff and mypy –strict | Move (25 exams and the demo diff) | Move (25 exams, the demo diff, ruff and mypy clear) |
| .NET construct and exams (10.0.115 on WSL, 10.0.404 on Home windows) | Move (exams and the demo diff) | Move (exams and the demo diff) |
| AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ exams, demo and pitfalls | Move (C 6 of 6, C++ 2 of two) | Not relevant |
| 5 pitfalls, every caught by the examine named in its part | Move (4 C checks, 1 C++ examine) | Not relevant |
| Form, delete, ordered-operation and set-benchmark experiments | Run on Ubuntu 24.04, output within the sections above | Not run |
Not coated: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 domestically (the CI matrix covers them), macOS, and timings on every other machine.

