Insert 100,000 keys into a binary search tree in sorted order and it becomes a list 99,999 levels deep. Insert the same keys shuffled and the height stays near 40. The keys are identical and the algorithm is identical. Only the insertion order decides whether the tree earns the O(log n) that the textbook promises. The same order also decides how expensive the interesting operations are: the predecessor, the successor, the floor, the ceiling and the k-th smallest key, all of which are what a search tree is really for.
This guide implements a binary search tree in C, C++, Java, Python and C# and measures what the basic descriptions skip. It shows how the height collapses under sorted input, what the three delete cases cost, and how many comparisons each ordered operation takes on a random tree. Every node also stores the size of its subtree, which makes rank and select a single walk down one path. The hand-written tree is then compared with the ordered containers the standard libraries already provide. Every program was built and tested on Ubuntu 24.04 under WSL2 with GCC and Clang, and on Windows 11 with MSVC, Java, Python and .NET. All five languages print the same demo output byte for byte, and every output block below comes from a real run.
What Is a Binary Search Tree?
A binary search tree is a binary tree with an ordering rule: every key in a node’s left subtree is smaller than the node’s key, and every key in its right subtree is larger. The rule turns each comparison into a step down the tree, so search, insert and delete cost O(height), which is O(log n) only when the tree is balanced.
The ordering rule is the whole structure. A search compares the target with the root and goes left or right, then repeats at the child. The path ends at the key or at an empty child, which proves the key is absent. The same rule makes the in-order traversal print the keys in ascending order, a fact the ordered operations rely on. The Binary Trees article covers the node layout, the four traversals and why a recursive walk overflows the call stack on a deep tree, so this article does not repeat them.
The ordered operations are the reason to keep the tree instead of a hash table. min and max walk to the leftmost and rightmost node. The successor of a key is the next key in sorted order. It is the leftmost node of the key’s right subtree or, when that subtree is empty, the lowest ancestor whose left subtree holds the key. The predecessor mirrors it.
The floor of a key is the largest stored key not greater than it, and the ceiling is the smallest stored key not less than it. Rank asks how many keys are smaller, and select returns the k-th smallest. Rank and select are the two operations that need the extra field this implementation stores in every node: the size of the subtree rooted there.
A search tree is only as good as its shape. The textbook O(log n) is an average over random insertion orders. Insert sorted keys and every new node goes to the right of the previous one, so the height becomes n – 1 and every operation becomes a linear scan with extra pointers. Balanced variants such as AVL and red-black trees keep the height logarithmic for every order and pay for it with rotations on insert and delete.
This article keeps the plain tree, measures the degeneration it cannot prevent, and shows what the ordered containers cost by comparison. The C++, Java and C# libraries ship red-black trees: std::set and std::map, TreeSet and TreeMap, and SortedSet<T> and SortedDictionary<TKey,TValue>. Python’s standard library has no balanced tree, and bisect over a sorted list is the usual substitute. The B-tree article covers the on-disk ordered structure that databases use when the index does not fit in memory.
How This Was Measured
| Setting | Value |
|---|---|
| Date tested | November 30, 2026 |
| Hardware | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300 |
| Operating system | Ubuntu 24.04.5 under WSL2, kernel 5.15.146, glibc 2.39; Windows 11 for the MSVC, Java and .NET builds |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 and -O3 through CMake Release; 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 |
| Shape experiment | 100,000 distinct keys: one shuffled permutation of 0 to 99,999 from a fixed xorshift64 seed, and the same keys in ascending order |
| Delete experiment | The random 100,000-key tree, every key deleted in a deterministic random order, classified by delete case before removal |
| Ordered-operations experiment | The random 100,000-key tree, 100,000 deterministic queries per operation, comparisons counted |
| Standard-library benchmark | 100,000 random inserts plus lookups, then 10,000 sorted inserts plus lookups, custom tree against std::set, median of 5 runs |
| What is timed | The comparisons and the insert, delete and lookup calls; key generation and tree destruction are outside the timed regions |
| Statistic | Heights and mean depths in edges; averages for comparison counts; median of 5 runs for timings, in milliseconds |
| Check | Every timing program prints a checksum of the values it read, and the benchmark’s two structures must agree on it |
No CPU pinning or frequency scaling control was used, and the host runs other software, so the timings are indicative for this machine and the ratios are the useful part. All heights, comparison counts and timings come from one machine and one WSL2 instance. The shape experiment’s sorted insertion is quadratic by construction, about 5e9 comparisons for 100,000 keys, so it is one run rather than a repeated median. The sorted tree is 99,999 levels deep, which is why its height and mean depth are computed with an explicit stack rather than recursion.
The Ordered Operations and Their Cost
| Operation | What it returns | Time |
|---|---|---|
| contains | Whether the key is stored | O(h) |
| insert | Adds a key if absent; duplicates are ignored | O(h) |
| delete | Removes a key through the leaf, one-child or two-child case | O(h) |
| min / max | Smallest and largest stored key | O(h) |
| successor / predecessor | Next larger and next smaller stored key | O(h) |
| floor / ceiling | Largest key not greater, smallest key not less | O(h) |
| rank | Number of stored keys strictly less than the given key | O(h) with subtree sizes |
| select | The key with exactly k stored keys smaller than it (rank-indexed: select(0) is the minimum, select(size – 1) the maximum) | O(h) with subtree sizes |
| in-order | Every key in ascending order | O(n) |
h is the height of the tree. For a balanced tree h is about log2 n, so a million keys need about 20 levels. For the degenerate sorted tree it is n – 1. The operations above never need more than one root-to-leaf path, and that is the promise the plain binary search tree breaks when the input arrives in order.
Binary Search Tree Implementation in C
C has no ordered container in its standard library, so the tree below is a complete implementation. Every node stores an int key, two child pointers and the size of its subtree. The tree structure holds only the root pointer, and the key count is the root’s subtree size. Absence is reported through bool out-parameters, so a stored value can never be confused with a missing answer, and the key type is int because C has no generics.
Search, Insert and the Ordered Walk
bool bst_insert(Bst *tree, int key)
{
BstNode *fresh = malloc(sizeof *fresh);
BstNode **link = &tree->root;
BstNode *node = NULL;
if (fresh == NULL)
return false;
while (*link != NULL) {
if (key == (*link)->key) {
free(fresh);
return false;
}
link = key < (*link)->key ? &(*link)->left : &(*link)->right;
}
fresh->key = key;
fresh->left = NULL;
fresh->right = NULL;
fresh->size = 1;
*link = fresh;
/* Every node above the new leaf gained one key. Walk the same path again
* so no array of parent links is needed. */
for (node = tree->root; node != fresh; ) {
node->size++;
node = key < node->key ? node->left : node->right;
}
return true;
}
bool bst_contains(const Bst *tree, int key)
{
const BstNode *node = tree->root;
while (node != NULL) {
if (key < node->key)
node = node->left;
else if (key > node->key)
node = node->right;
else
return true;
}
return false;
}
/* The number of stored keys strictly less than key. */
size_t bst_rank(const Bst *tree, int key)
{
const BstNode *node = tree->root;
size_t rank = 0;
while (node != NULL) {
if (key <= node->key) {
node = node->left;
} else {
rank += node_size(node->left) + 1;
node = node->right;
}
}
return rank;
}
/* The key with exactly k stored keys smaller than it: select(0) is the
* minimum, select(size - 1) is the maximum, and rank(select(k)) is k. Returns
* false when k is outside 0 to size - 1. */
bool bst_select(const Bst *tree, size_t k, int *out)
{
const BstNode *node = tree->root;
if (k >= bst_size(tree))
return false;
while (node != NULL) {
size_t left = node_size(node->left);
if (k < left) {
node = node->left;
} else if (k == left) {
*out = node->key;
return true;
} else {
k -= left + 1;
node = node->right;
}
}
return false;
}
The search is the ordering rule in code: compare, go left when the key is smaller, right when it is larger, and stop at an empty pointer to prove absence. Insert repeats the walk and attaches a new leaf, and a duplicate key is found on the way and changes nothing.
Because every node knows its subtree size, rank is the same walk with a running count. It adds the left subtree’s size plus one whenever the key is larger than the node, goes left otherwise, and runs down to an empty pointer. Select walks the sizes instead of the keys, going left when k is below the left subtree’s size, right when it is above, and returning the node when the remainder is zero. Min and max are the ends of that walk, and successor and predecessor each have a right-subtree case and an ancestor case.
Erasing a Node
bool bst_erase(Bst *tree, int key)
{
BstNode **link = &tree->root;
BstNode *node = NULL;
BstNode **succ_link = NULL;
BstNode *succ = NULL;
BstNode **step = NULL;
while (*link != NULL && (*link)->key != key)
link = key < (*link)->key ? &(*link)->left : &(*link)->right;
node = *link;
if (node == NULL)
return false;
if (node->left == NULL || node->right == NULL) {
BstNode *child = node->left != NULL ? node->left : node->right;
lose_one_on_path(tree, key, link);
*link = child;
free(node);
return true;
}
succ_link = &node->right;
while ((*succ_link)->left != NULL)
succ_link = &(*succ_link)->left;
succ = *succ_link;
lose_one_on_path(tree, key, link);
node->size--;
for (step = &node->right; step != succ_link; step = &(*step)->left)
(*step)->size--;
*succ_link = succ->right;
node->key = succ->key;
free(succ);
return true;
}
The delete function walks with a pointer to the link that holds the current node, so removing the root needs no special case: writing through link replaces whatever pointed at the node. A leaf is freed and its link becomes NULL, and a node with one child is replaced by that child. A node with two children takes the key of its in-order successor, and the successor, which has no left child, is unlinked from the right subtree and freed.
Before any pointer changes, lose_one_on_path walks from the root to the removed position and decrements every subtree size on the way. The two-child case also decrements the sizes on the path down to the successor. That keeps rank and select correct after every delete.
The tree is freed with an explicit loop that rotates each left child up before moving down, so a 100,000-level sorted tree is released without recursing. The tests free a 100,000-node random tree and a 10,000-key sorted chain, and the sanitizer job runs them under LeakSanitizer.
The C Demo
The demo builds the tree that Figure 1 uses, then exercises one operation at a time: the ordered queries first, then the three delete cases, then a duplicate insert that must leave the size unchanged.
Output:
binary search tree, ordered operations
insert 50, 30, 70, 20, 40, 60, 80, 25 -> size 8, height 3
min 20, max 80
contains 40 -> true, contains 45 -> false
floor 45 -> 40, ceiling 45 -> 50
rank 40 -> 3, select 3 -> 40
in-order: 20 25 30 40 50 60 70 80
successor 40 -> 50, predecessor 40 -> 30
delete 20 (one child) -> size 7, in-order: 25 30 40 50 60 70 80
delete 25 (leaf) -> size 6, in-order: 30 40 50 60 70 80
delete 50 (two children) -> size 5, in-order: 30 40 60 70 80
insert 60 -> size 5
Binary Search Tree Implementation in C++
In C++ the same design becomes a class template over the key type and a comparator, with std::optional for absence and std::unique_ptr for the nodes. The ordered API is complete: insert, contains, erase, min, max, successor, predecessor, floor, ceiling, rank, select, height, size and in-order.
bool insert(K key)
{
std::unique_ptr<Node>* link = &root_;
while (*link) {
if (comp_(key, (*link)->key))
link = &(*link)->left;
else if (comp_((*link)->key, key))
link = &(*link)->right;
else
return false; // neither key compares before the other
}
*link = std::make_unique<Node>(std::move(key));
Node* inserted = link->get();
// The ancestors are still above the new node: count it in each of them.
Node* ancestor = root_.get();
while (ancestor != inserted) {
++ancestor->subtree_size;
ancestor = comp_(inserted->key, ancestor->key) ? ancestor->left.get()
: ancestor->right.get();
}
++size_;
return true;
}
bool erase(const K& key)
{
std::vector<Node*> ancestors;
std::unique_ptr<Node>* link = &root_;
while (*link) {
if (comp_(key, (*link)->key)) {
ancestors.push_back(link->get());
link = &(*link)->left;
} else if (comp_((*link)->key, key)) {
ancestors.push_back(link->get());
link = &(*link)->right;
} else {
break;
}
}
if (!*link)
return false; // the key is not in the tree
for (Node* ancestor : ancestors)
--ancestor->subtree_size;
Node* node = link->get();
if (!node->left || !node->right) {
// A leaf, or one child: the child, if any, takes the node's place.
// Move the child out first; assigning over the node frees it.
std::unique_ptr<Node> child =
std::move(node->left ? node->left : node->right);
*link = std::move(child);
} else {
// Two children: copy the in-order successor's key into the node and
// unlink the successor, which has no left child.
std::unique_ptr<Node>* successor_link = &node->right;
std::vector<Node*> successor_ancestors;
while ((*successor_link)->left) {
successor_ancestors.push_back(successor_link->get());
successor_link = &(*successor_link)->left;
}
Node* successor = successor_link->get();
node->key = std::move(successor->key);
--node->subtree_size;
for (Node* ancestor : successor_ancestors)
--ancestor->subtree_size;
std::unique_ptr<Node> right = std::move(successor->right);
*successor_link = std::move(right);
}
--size_;
return true;
}
// Number of keys strictly less than key. O(height): each step adds the
// whole left subtree of a node that compares before the key.
[[nodiscard]] size_type rank(const K& key) const
{
size_type less = 0;
const Node* node = root_.get();
while (node != nullptr) {
if (comp_(node->key, key)) {
less += node_size(node->left.get()) + 1;
node = node->right.get();
} else {
node = node->left.get();
}
}
return less;
}
// The key with exactly k stored keys smaller than it: select(0) is the
// minimum and select(size - 1) is the maximum, so rank(select(k)) == k.
// Absent when k is outside 0 to size - 1.
[[nodiscard]] std::optional<K> select(size_type k) const
{
if (k >= size_)
return std::nullopt;
const Node* node = root_.get();
while (node != nullptr) {
const size_type left = node_size(node->left.get());
if (k < left) {
node = node->left.get();
} else if (k == left) {
return std::optional<K>(node->key);
} else {
k -= left + 1;
node = node->right.get();
}
}
return std::nullopt; // unreachable while the sizes are correct
}
Two details differ from the C version. The comparator is a template parameter defaulting to std::less<K>, so the tree orders any type with a strict weak ordering, including std::string. And absence is an empty std::optional, so the value type does not need a sentinel, while rank still returns a plain std::size_t.
std::set, the Balanced Alternative
For production C++, use std::set or std::map from <set> and <map>. They are ordered containers implemented as red-black trees: insert, erase, find, lower_bound, upper_bound and the ordered iteration all cost O(log n) for every insertion order, not only random ones. lower_bound returns the ceiling (the first key not less than the argument), upper_bound returns the strict successor, and std::prev of upper_bound gives the floor. The price is a constant factor that the benchmark measures, and the benefit is that the logarithm cannot be lost to a bad input order. The STL containers guide covers the rest of that container family.
The comparison the containers cannot do as directly is rank and select. std::set has no order-statistics operations, so a program that needs them either stores subtree sizes in its own tree, as this article does, or pays O(n) to walk to the k-th element. That is the one case where the hand-written ordered tree earns its complexity.
The C++ Demo
The C++ demo prints exactly the same bytes as the C program, and the build compares it against the same expected file. The std::set benchmark later in the article uses the same 100,000 random keys and the sorted case that breaks the plain tree.
Binary Search Tree Implementation in Java, Python and C#
The three versions follow the C design with generic keys: a subtree size per node, iterative walks, and absence reported through the language’s idiomatic empty result. Their standard libraries differ in what they provide. Java has TreeSet and TreeMap, red-black trees with the full ordered API except rank and select. C# has SortedSet<T> and SortedDictionary<TKey,TValue>, also red-black trees. Python’s standard library has no balanced tree at all. bisect over a sorted list gives binary search and insertion by index, and a third-party package is needed for an ordered map.
Java
public boolean put(E key) {
Objects.requireNonNull(key, "null values are not supported: null reports absence");
if (root == null) {
root = new Node<>(key);
return true;
}
List<Node<E>> path = new ArrayList<>();
Node<E> node = root;
while (true) {
int compare = key.compareTo(node.key);
if (compare == 0) {
return false;
}
path.add(node);
Node<E> next = compare < 0 ? node.left : node.right;
if (next == null) {
if (compare < 0) {
node.left = new Node<>(key);
} else {
node.right = new Node<>(key);
}
for (Node<E> ancestor : path) {
ancestor.size++; // the new key joins every subtree on the path
}
return true;
}
node = next;
}
}
public boolean remove(E key) {
Objects.requireNonNull(key, "null values are not supported: null reports absence");
List<Node<E>> path = new ArrayList<>();
Node<E> node = root;
while (node != null) {
int compare = key.compareTo(node.key);
if (compare == 0) {
break;
}
path.add(node);
node = compare < 0 ? node.left : node.right;
}
if (node == null) {
return false;
}
if (node.left != null && node.right != null) {
// Two children: copy the successor's key in, then unlink the successor,
// which has no left child. This keeps the in-order sequence and the
// subtree sizes around it correct.
Node<E> successor = node.right;
List<Node<E>> descent = new ArrayList<>();
while (successor.left != null) {
descent.add(successor);
successor = successor.left;
}
node.key = successor.key;
if (descent.isEmpty()) {
node.right = successor.right;
} else {
descent.get(descent.size() - 1).left = successor.right;
}
for (Node<E> ancestor : path) {
ancestor.size--;
}
for (Node<E> below : descent) {
below.size--;
}
node.size--;
} else {
// Zero or one child: replace the node with its only child, or with null.
Node<E> child = node.left != null ? node.left : node.right;
if (path.isEmpty()) {
root = child;
} else {
Node<E> parent = path.get(path.size() - 1);
if (parent.left == node) {
parent.left = child;
} else {
parent.right = child;
}
}
for (Node<E> ancestor : path) {
ancestor.size--;
}
}
return true;
}
The class is generic over E extends Comparable<E>, so the ordering comes from compareTo and the tree needs no comparator parameter. Absence is null, and the class rejects null keys for that reason. rank and select use the stored subtree sizes, and select is rank-indexed, so rank and select are exact inverses. The tests compare it against a sorted ArrayList model.
In application code, TreeSet and TreeMap give the same ordered operations with a red-black tree underneath. floor, ceiling, lower, higher, first and last are the method names to look for, and subSet returns a range view. Neither offers rank or select, for the same reason as C++.
Python
def _insert(root: _Node[K] | None, key: K) -> tuple[_Node[K], bool]:
"""Insert a key under root, returning the new root and whether it was new.
The walk is a loop, so sorted input that builds a chain as deep as the tree
is large cannot hit Python's recursion limit.
"""
if root is None:
return _Node(key), True
path: list[_Node[K]] = []
node = root
while 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.right is None:
node.right = _Node(key)
break
node = node.right
else:
return root, False
for ancestor in path:
ancestor.size += 1
return root, True
def _erase(root: _Node[K] | None, key: K) -> tuple[_Node[K] | None, bool]:
"""Erase a key under root, returning the new root and whether it was there.
The leaf and one-child cases unlink the node. The two-child case copies the
in-order successor's key into the node and then unlinks the successor, which
has no left child, so the tree keeps the same in-order sequence.
"""
path: list[_Node[K]] = []
node = root
while node is not None:
if key < node.key:
path.append(node)
node = node.left
elif node.key < key:
path.append(node)
node = node.right
else:
break
if node is None:
return root, False
for ancestor in path:
ancestor.size -= 1
if node.left is not None and node.right is not None:
node.size -= 1
parent = node
successor = node.right
while successor.left is not None:
successor.size -= 1
parent = successor
successor = successor.left
node.key = successor.key
if parent is node:
parent.right = successor.right
else:
parent.left = successor.right
return root, True
child = node.left if node.left is not None else node.right
if not path:
return child, True
parent = path[-1]
if parent.left is node:
parent.left = child
else:
parent.right = child
return root, True
def rank(self, key: K) -> int:
"""Return the number of keys strictly less than key."""
count = 0
node = self._root
while node is not None:
if key < node.key:
node = node.left
elif node.key < key:
count += _size(node.left) + 1
node = node.right
else:
return count + _size(node.left)
return count
def select(self, k: int) -> K | None:
"""Return the key whose rank is k, or None when k is outside 0 to size - 1.
The rank is the number of stored keys strictly less than the key, so
select(0) is the minimum and rank(select(k)) is k.
"""
node = self._root
while node is not None:
left = _size(node.left)
if k < left:
node = node.left
elif k == left:
return node.key
else:
k -= left + 1
node = node.right
return None
The ordering comes from the key type’s < operator, and absence is None, so insert(None) raises TypeError. Every walk is a loop, including the height and the in-order traversal, because a recursive version stops with RecursionError once sorted input builds a chain deeper than the default limit of 1,000 frames. The tests build and empty a 5,000-key sorted chain to prove it, and compare everything else against a bisect-maintained sorted list.
For application code, Python’s standard library offers bisect over a sorted list: binary search, the insertion point (which is the floor or ceiling position), and O(n) insertion because the list shifts. For an ordered map that needs the tree’s asymptotics, third-party packages such as sortedcontainers are the usual answer. The built-in dict keeps insertion order, not key order, so it cannot answer 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: each of them gains one key in its subtree.
var path = new List<Node>();
Node node = _root;
while (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.Right is null)
{
node.Right = new Node(key);
break;
}
node = node.Right;
}
}
foreach (Node ancestor in path)
ancestor.Size++;
return true;
}
public bool Remove(TKey key)
{
ArgumentNullException.ThrowIfNull(key);
// Ancestors of the node that is actually unlinked, root first. Every
// one of them loses one key from its subtree size.
var ancestors = new List<Node>();
Node? node = _root;
while (node is not null)
{
int order = key.CompareTo(node.Key);
if (order == 0)
break;
ancestors.Add(node);
node = order < 0 ? node.Left : node.Right;
}
if (node is null)
return false;
if (node.Left is not null && node.Right is not null)
{
// Two children: move to the in-order successor, the leftmost node
// of the right subtree, then unlink the successor. It has no left
// child, so unlinking it is the easy case.
Node successorParent = node;
Node successor = node.Right;
node.Size--;
while (successor.Left is not null)
{
successorParent = successor;
successorParent.Size--;
successor = successor.Left;
}
node.Key = successor.Key;
Node? child = successor.Right;
if (successorParent == node)
successorParent.Right = child;
else
successorParent.Left = child;
}
else
{
Node? child = node.Left ?? node.Right;
if (ancestors.Count == 0)
_root = child;
else if (ancestors[^1].Left == node)
ancestors[^1].Left = child;
else
ancestors[^1].Right = child;
}
foreach (Node ancestor in ancestors)
ancestor.Size--;
return true;
}
The C# class is generic over TKey with an IComparable<TKey> constraint, uses a Try...-style out result for absence, and keeps the same subtree-size augmentation. The tests compare it against SortedSet<TKey> and a sorted-list model, and check the rank and select boundaries.
In application code, SortedSet<T> and SortedDictionary<TKey,TValue> are the red-black-tree containers. GetViewBetween returns a range view, Min and Max are properties, and there is no rank or select. They are the closest library equivalents to the tree built here.
Height on Random and Sorted Input
The shape experiment inserts the same 100,000 keys twice: once as a shuffled permutation, once in ascending order. It reports the height, the mean depth, the build time and the average comparisons for 10,000 lookups. The sorted tree reaches 99,999 levels, so every measurement in the program uses an explicit loop rather than recursion. The Binary Trees article measures where the recursive walk overflows instead.
static bool tree_stats(const Node *root, int *height, double *mean_depth)
{
NodeVec level = { NULL, 0, 0 };
NodeVec next = { NULL, 0, 0 };
unsigned long long total_depth = 0;
size_t count = 0;
int depth = -1;
bool ok = true;
if (root != NULL)
ok = vec_push(&level, root);
while (ok && level.len > 0) {
size_t i;
depth++;
total_depth += (unsigned long long)depth *
(unsigned long long)level.len;
count += level.len;
next.len = 0;
for (i = 0; i < level.len; ++i) {
if (level.items[i]->left != NULL)
ok = vec_push(&next, level.items[i]->left);
if (ok && level.items[i]->right != NULL)
ok = vec_push(&next, level.items[i]->right);
}
{
NodeVec swap = level;
level = next;
next = swap;
}
}
free(level.items);
free(next.items);
if (!ok)
return false;
*height = depth;
*mean_depth = count == 0 ? 0.0 : (double)total_depth / (double)count;
return true;
}
Output:
100,000 keys, height and mean depth in edges
build order height 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: size 75000 height 39
after 50000 deletions: size 50000 height 36
after 75000 deletions: size 25000 height 33
The random 100,000-key tree came out 40 levels high with a mean depth of 19.92 edges, and the sorted tree 99,999 levels high with a mean depth of 49,999.50. The textbook expectation for a random tree is a mean depth near 2H_n – 4, about 20.2 for this n, and the measured 19.92 agrees to within 1.5%. The asymptotic formula for the expected height, 4.311 ln n – 1.953 ln ln n, gives about 45, but it converges slowly and overstates the height at this size. The mean depth, whose exact expectation is known, is the sharper check.
The build time separates the two orders more sharply than any count: 18 ms for the shuffled keys against 14,606 ms for the ascending ones, about 800 times longer for the same inserts, because the ascending build makes roughly 5e9 comparisons. The sampled lookups tell the same story, 20.94 comparisons on the random tree against 49,948 on the sorted one. Deleting a quarter, half and three quarters of the keys shrank the random tree from height 40 to 39, 36 and 33, so deletion prunes the tree without rebalancing it.
Deleting a Node: Leaf, One Child, Two Children
Deletion is the operation that separates a tree that works on paper from one that passes a model test. A leaf disappears. A node with one child is replaced by that child. A node with two children cannot simply be removed, because both subtrees have to stay. The standard move finds the in-order successor, the smallest key in the right subtree, copies its key over the node’s key, and then deletes that successor, which has no left child.
The demo output in the C section shows the three cases in order: 20 has one child (25), 25 is a leaf by the time it is deleted, and 50 has two children, so the successor 60 takes its place. The in-order row after each delete is what proves the ordering survived.
The delete experiment runs the three cases at scale on the random 100,000-key tree and counts the comparisons each delete spends finding its key, grouped by the case the node was in before removal:
static int erase_classified(Node **root, int key,
unsigned long long *comparisons)
{
Node **link = root;
Node *node;
int which;
while (*link != NULL) {
(*comparisons)++;
if (key < (*link)->key)
link = &(*link)->left;
else if (key > (*link)->key)
link = &(*link)->right;
else
break;
}
node = *link;
if (node == NULL)
return CASE_COUNT;
if (node->left == NULL && node->right == NULL)
which = CASE_LEAF;
else if (node->left != NULL && node->right != NULL)
which = CASE_TWO;
else
which = CASE_ONE;
if (node->left != NULL && node->right != NULL) {
Node **succ_link = &node->right;
Node *succ;
while ((*succ_link)->left != NULL)
succ_link = &(*succ_link)->left;
succ = *succ_link;
*succ_link = succ->right;
node->key = succ->key;
node = succ;
} else if (node->left != NULL) {
*link = node->left;
} else {
*link = node->right;
}
free(node);
return which;
}
Output:
random tree, 100,000 keys, deletion in random order
case deletions avg_comparisons
leaf 34035 20.13
one child 32257 19.22
two children 33708 17.22
final size 0, empty true
The random deletion order put 34,035 leaves, 32,257 one-child nodes and 33,708 two-child nodes through the three cases. The average comparisons are close: 20.13 for a leaf, 19.22 for a one-child node and 17.22 for a two-child node. The two-child case is the cheapest here, not because copying the successor is free, but because a node with two children cannot sit at the bottom of the tree: it is above the leaves, so the search reaches it in fewer comparisons. The expensive part of deletion is the height of the tree the search has to walk, and the case distribution barely changes that walk.
What the Ordered Operations Cost
The operations that justify a search tree over a hash table are the ordered ones. The experiment runs 100,000 deterministic queries per operation on the same random 100,000-key tree and counts comparisons:
static size_t tree_rank(const Node *node, int key,
unsigned long long *comparisons)
{
size_t rank = 0;
while (node != NULL) {
(*comparisons)++;
if (key <= node->key) {
node = node->left;
} else {
rank += node_size(node->left) + 1;
node = node->right;
}
}
return rank;
}
/* select compares no keys: it follows the subtree sizes. */
static bool tree_select(const Node *node, size_t k, int *out)
{
if (k >= node_size(node))
return false;
while (node != NULL) {
size_t left = node_size(node->left);
if (k < left) {
node = node->left;
} else if (k == left) {
*out = node->key;
return true;
} else {
k -= left + 1;
node = node->right;
}
}
return false;
}
Output:
100,000-key random tree
operation queries avg_comparisons
contains 100000 20.92
min 100000 0.00
max 100000 0.00
successor 100000 21.93
predecessor 100000 21.92
floor 100000 21.93
ceiling 100000 21.92
rank 100000 21.92
select 100000 0.00
Every key-based operation averaged about 21 comparisons on this tree, from 20.92 for contains to 21.93 for successor, floor and ceiling, close to the 19.92 mean depth of the tree. Each operation walks one root-to-leaf path and compares once per node.
The three zeros are the operations that do not compare keys at all. min and max follow child pointers only, and select compares the requested rank with subtree sizes, so none of them performs a key comparison. Rank is not in that group, because it compares the key at every node on its path, and its 21.92 is that walk. The practical reading is that the augmented tree makes rank no more expensive than contains: the same path, plus a few additions.
Custom Tree Against std::set
The standard library’s ordered container is a balanced tree, and the benchmark compares the hand-written tree with it. The random case shows the constant factor of two implementations of the same idea, and the sorted case shows the price of not balancing.
int main()
{
const std::vector<int> random_keys = shuffled_keys(kRandomKeys);
const std::vector<int> sorted_keys = ascending_keys(kSortedKeys);
const Result custom_random = median_run([&random_keys] {
return run_custom_once(random_keys);
});
const Result std_random = median_run([&random_keys] {
return run_std_once(random_keys);
});
const Result custom_sorted = median_run([&sorted_keys] {
return run_custom_once(sorted_keys);
});
const Result 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 containers\n");
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("custom BST %.1f\n", custom_random.ms);
std::printf("std::set %.1f\n", std_random.ms);
std::printf("10,000 sorted inserts + lookups, median of 5 runs (ms)\n");
std::printf("custom BST %.1f\n", custom_sorted.ms);
std::printf("std::set %.1f\n", std_sorted.ms);
std::printf("checksum: %llu\n",
static_cast<unsigned long long>(checksum));
return EXIT_SUCCESS;
}
Output:
100,000 random inserts + lookups, median of 5 runs (ms)
custom BST 67.1
std::set 34.3
10,000 sorted inserts + lookups, median of 5 runs (ms)
custom BST 1860.1
std::set 1.1
checksum: 4630652801823639509
On random input, 100,000 inserts and lookups took 67.1 ms in the custom tree and 34.3 ms in std::set: the red-black tree was about twice as fast for the same asymptotics, most likely because the custom insert walks the path a second time to update subtree sizes and the random tree is taller than a red-black tree of the same keys. On 10,000 sorted inserts and lookups the gap becomes the whole point: 1,860.1 ms for the custom tree against 1.1 ms for std::set, about 1,700 times slower, because the sorted custom tree is a list of 9,999 levels while the red-black tree stays logarithmic regardless of insertion order.
The custom tree’s advantage is not speed. It is the rank and select operations the library does not expose, and the benchmark shows what that control costs on this machine.
Five Ways a Binary Search Tree Passes a Quick Test and Still Fails
Each of these programs compiles cleanly with -Wall -Wextra -pedantic and prints something plausible until the line below it. The first four live in the C repository’s pitfalls/ directory and the fifth in the C++ repository’s; the workflows re-run each and assert the line or sanitizer summary that shows the bug.
1. A Successor Without the Ancestor Case
static bool successor_buggy(const Node *root, int key, int *out)
{
const Node *node = root;
while (node != NULL && node->key != key)
node = key < node->key ? node->left : node->right;
if (node == NULL || node->right == NULL)
return false;
node = node->right;
while (node->left != NULL)
node = node->left;
*out = node->key;
return true;
}
Output:
successor_no_ancestor: a successor that only looks right
successor 30 -> 40, expected 40
successor 60 -> none, expected 70
The buggy successor only knows the right-subtree case. For 30 it returns 40 correctly, because 40 is the leftmost node of 30’s right subtree. For 60, whose right subtree is empty, it returns none, but the answer is the ancestor 70. The fix is the second half of the algorithm: walk down from the root, remembering the last ancestor from which the search turned left.
2. Floor and Ceiling on the Wrong Side
static bool floor_buggy(const Node *root, int key, int *out)
{
const Node *node = root;
const Node *best = NULL;
while (node != NULL) {
if (node->key >= key) {
best = node;
node = node->left;
} else {
node = node->right;
}
}
if (best == NULL)
return false;
*out = best->key;
return true;
}
/* The bug: the mirror image, so this returns the floor. */
static bool ceiling_buggy(const Node *root, int key, int *out)
{
const Node *node = root;
const Node *best = NULL;
while (node != NULL) {
if (node->key <= key) {
best = node;
node = node->right;
} else {
node = node->left;
}
}
if (best == NULL)
return false;
*out = best->key;
return true;
}
Output:
floor_ceiling_swapped: floor and ceiling with the comparison reversed
floor 45 -> 50, expected 40
ceiling 45 -> 40, expected 50
Reversing the comparison turns floor into ceiling and ceiling into floor: floor(45) returns 50 and ceiling(45) returns 40. The functions look plausible in isolation and fail only for keys that are not stored. They are the same walk with the candidate update on the correct side, which is the fix.
3. A Two-Child Delete That Leaks the Successor
static bool erase_buggy(Node **root, int key)
{
Node **link = root;
Node *node;
while (*link != NULL && (*link)->key != key)
link = key < (*link)->key ? &(*link)->left : &(*link)->right;
node = *link;
if (node == NULL)
return false;
if (node->left != NULL && node->right != NULL) {
Node **succ_link = &node->right;
Node *succ;
while ((*succ_link)->left != NULL)
succ_link = &(*succ_link)->left;
succ = *succ_link;
*succ_link = succ->right;
node->key = succ->key;
return true; /* the successor node is never freed */
}
*link = node->left != NULL ? node->left : node->right;
free(node);
return true;
}
Output:
delete_two_children_leak: the successor node is unlinked but not freed
in-order after delete 50: 20 30 40 60 70 80
Output (summarized from the LeakSanitizer report):
AddressSanitizer: LeakSanitizer detected a memory leak
Direct leak of 24 byte(s) in 1 object(s)
allocated at delete_two_children_leak.c:30
The erase path relinks the successor’s child and copies the successor’s key, but never frees the successor node. The in-order output is correct and the tree looks right, while LeakSanitizer reports a direct leak of 24 bytes, one node. A two-child delete frees exactly one node, and the case is easy to miss because the visible output never shows the leak.
4. Duplicate Keys Through the Right Branch
static Node *insert_buggy(Node *root, int key)
{
Node **link = &root;
while (*link != NULL)
link = key < (*link)->key ? &(*link)->left : &(*link)->right;
*link = malloc(sizeof **link);
if (*link == NULL) {
fputs("out of memory\n", stderr);
exit(EXIT_FAILURE);
}
(*link)->key = key;
(*link)->left = NULL;
(*link)->right = NULL;
return root;
}
Output:
duplicate_keys: insert sends equal keys right and never checks
insert 40 twice -> size 2, expected 1
in-order: 40 40
insert 60 -> size 3, expected 2
rank 60 -> 2, expected 1
Equality sent to the right without a check stores 40 twice: size 2, an in-order row of 40 40, and rank 60 counts the duplicate and returns 2 instead of 1. The fix is one comparison before the walk continues, because every ordered operation relies on there being exactly one node per key.
5. A Reference Into a std::set Across an Erase
// dangling_set_reference.cpp - DO NOT COPY. A reference to a std::set element
// is valid only while that element stays in the set. erase() destroys the node,
// so the reference dangles and the read is undefined behaviour; AddressSanitizer
// reports heap-use-after-free.
// Build: g++ -std=c++17 -Wall -Wextra -pedantic -g -fsanitize=address pitfalls/dangling_set_reference.cpp -o dangling_set_reference
#include <iostream>
#include <set>
int main()
{
std::set<int> values{40, 50, 60};
const int& reference = *values.find(50);
std::cout << "dangling_set_reference: reference into std::set across erase\n";
std::cout << "before erase: " << reference << '\n';
values.erase(values.find(50));
std::cout << "size after erase: " << values.size() << '\n';
std::cout.flush();
// The node that held 50 was freed by erase(). Reading reference here is
// the heap-use-after-free that AddressSanitizer reports.
std::cout << "stale value: " << reference << '\n';
return 0;
}
Output:
AddressSanitizer: heap-use-after-free
READ of size 4 at pitfalls/dangling_set_reference.cpp:22
32 bytes inside a 40-byte region 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 main
A reference into a std::set is valid only while its element stays in the set. The program prints 50 before the erase and then reads the same reference after it, and AddressSanitizer reports a heap-use-after-free because the node went back to the allocator. Copy the value out before erasing, or keep an iterator and erase it only when the value is no longer needed.
Key Takeaways
- The ordering rule turns comparisons into a path, so every ordered operation costs O(height). The tree keeps its O(log n) promise only while it stays balanced.
- Inserting 100,000 keys in sorted order produced a tree 99,999 levels deep, against 40 for the same keys shuffled, which is the difference between a tree and a list.
- The subtree size in each node makes rank and select one root-to-leaf walk, and the two are exact inverses when select is rank-indexed.
- The three delete cases are one algorithm once the successor is defined: a leaf is unlinked, a one-child node is replaced, and a two-child node takes its successor’s key.
- A random 100,000-key tree gives every ordered operation a short path, about 21 comparisons against a mean depth of 19.92.
std::setwon both benchmark cases on this machine, 34.3 ms against 67.1 ms on random input and 1.1 ms against 1,860.1 ms on sorted input. The hand-written tree’s value is the rank and select operations the library does not expose, not raw speed.- Successor, predecessor, floor and ceiling are the same walk with a different rule for remembering the candidate, and getting that rule wrong is the bug behind pitfalls 1 and 2.
Frequently Asked Questions
Conclusion
The binary search tree is the structure where the average case hides the whole story. Its operations are short walks when the shape is good and linear scans when the input arrives sorted, and the same 40 against 99,999 levels separate the two cases here. The ordered operations, and the subtree sizes that make rank and select cheap, are the part a hash table cannot provide. The degeneration is the part the balanced containers exist to prevent.
In production code, use the library’s balanced container unless rank and select or a custom traversal are required, and if the insertion order is not under the program’s control, use it anyway. For a key lookup with no ordering, the hash table is the faster tool. The types of data structures guide shows where the search tree sits among the others, and the data structures hub lists every article in the series.
Source Code and Tests
All programs on this page are in the data-structures/binary-search-tree directory of the five MYCPLUS example repositories:
The C and C++ examples build and test with CMake:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
Java runs with javac --release 17 -Xlint:all -Werror -d build src/*.java tests/*.java followed by java -ea -cp build BstTest. Python runs with python -m unittest discover -s tests -v, and C# with dotnet build BinarySearchTree.slnx -c Release followed by dotnet run --project tests/BstTests -c Release --no-build.
What the builds check. Every demo’s stdout is compared byte for byte with tests/expected/ordered.txt. The tests compare every operation against a sorted-array model over at least 100,000 random operations (200,000 in C), check the subtree sizes against an independent count, cross-check rank and select, and cover the boundaries, an empty tree and a delete-and-reinsert churn. The C and C++ workflows also run the tests, demo and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer, and the C workflow checks the leak reported by the two-child delete pitfall. The builds do not check the height, comparison or timing figures: those belong to one machine and are captured with the article.
What I Verified
The example directories contain the test programs and the captured runs, and the table states which system ran each check.
| Check | Ubuntu 24.04 (WSL2) | Windows 11 (MSVC) |
|---|---|---|
| Build and tests, C, GCC 13.3 | Pass (6 of 6 tests) | Not applicable |
| Build and tests, C, Clang 18.1.3 | Pass (6 of 6 tests) | Not applicable |
Build and tests, C, MSVC 19.44 /W4 /WX | Not applicable | Pass (6 of 6 tests) |
| Build and tests, C++, g++ 13.3 | Pass (2 of 2 tests) | Not applicable |
| Build and tests, C++, clang++ 18.1.3 | Pass (2 of 2 tests) | Not applicable |
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive- | Not applicable | Pass (2 of 2 tests) |
| Java tests (JDK 21 on WSL, JDK 27 on Windows) | Pass (tests and the demo diff) | Pass (tests and the demo diff) |
| Python tests (3.12.3 on WSL, 3.14.6 on Windows), ruff and mypy –strict | Pass (25 tests and the demo diff) | Pass (25 tests, the demo diff, ruff and mypy clean) |
| .NET build and tests (10.0.115 on WSL, 10.0.404 on Windows) | Pass (tests and the demo diff) | Pass (tests and the demo diff) |
| AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ tests, demo and pitfalls | Pass (C 6 of 6, C++ 2 of 2) | Not applicable |
| Five pitfalls, each caught by the check named in its section | Pass (4 C checks, 1 C++ check) | Not applicable |
| Shape, delete, ordered-operation and set-benchmark experiments | Run on Ubuntu 24.04, output in the sections above | Not run |
Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 locally (the CI matrix covers them), macOS, and timings on any other machine.




