Binary Search Trees
Ordered keys, O(height) operations, and why height is everything.
A sorted array finds any of a million keys in 20 comparisons, but inserting one new key can shift a million others. A binary search tree keeps the 20-comparison search and makes insertion cheap too, as long as the tree stays short. Feed it the same million keys in sorted order, though, and every search becomes a walk down a million-node chain.
What you’ll learn
- State the binary-search-tree property and use it to search, find the minimum and maximum, and insert in time, where is the height.
- Find successors, predecessors, floors and ceilings, and delete a key in all three cases, proving that the BST property survives.
- Explain why the height decides everything: ranges from to , and random insertion orders give average depth .
- Recognize ordered-set problems (successor, floor, ceiling, nearest value under insertions and deletions) and solve them with the library's ordered set, choosing a hash set or a heap when order is not needed.
The BST property, and search along one path
A binary search tree (BST) stores one key per node, and each node has a left and a right child, either of which may be missing. What makes it a search tree is one rule about whole subtrees, not just about children:
Searching for a key uses the property the way binary search uses a sorted array. Compare with the root: if they are equal, stop; if is smaller, every candidate lies in the left subtree, so go left; if larger, go right. The loop invariant is if is in the tree, it is in the subtree of the current node. Each comparison moves one level down, so a search makes at most comparisons, where is the tree's height (heights count edges: a single node has height 0). The minimum sits at the end of the leftmost path, the maximum at the end of the rightmost one.
Insertion is an unsuccessful search: walk down until you fall off the tree, and hang the new key exactly where you fell off.
class Node:
__slots__ = ('key', 'left', 'right')
def __init__(self, key):
self.key, self.left, self.right = key, None, None
def search(x, key): # O(h): follows one downward path
while x is not None and key != x.key:
x = x.left if key < x.key else x.right
return x # the node holding key, or None
def insert(x, key): # returns the root of the updated subtree
if x is None:
return Node(key)
if key < x.key:
x.left = insert(x.left, key)
elif key > x.key:
x.right = insert(x.right, key)
return x # an equal key is already presentIterative search, recursive insertion. Both follow one root-to-leaf path, so both take time. Insertion returns the root of the updated subtree so that the parent's pointer can be reset, a pattern deletion reuses below.
Sorted order for free: inorder, successor, predecessor
Two consequences. First, inserting keys and then walking the tree sorts them (tree sort), so in the comparison model building a BST of keys takes comparisons in the worst case: no comparison-based search tree can make every insertion cost , even amortized. Second, questions about order become walks along a path.
The successor of is the next key in sorted order, found in one of two places. If has a right subtree, it is that subtree's minimum: go right once, then left as far as possible. Otherwise it is the lowest ancestor of whose left subtree contains : climb until you arrive at a node from its left child. The predecessor is the mirror image, and both cost .
Without parent pointers, a single downward walk does the job, and it works even when the query key is not stored, which turns it into a strictly higher or ceiling query:
def successor(root, key): # smallest stored key > key, or None
best, x = None, root
while x is not None:
if x.key > key:
best, x = x.key, x.left # a candidate; look for a smaller one
else:
x = x.right # x and its left subtree are all <= key
return bestThe last node where the walk turned left is the answer, because every key met after it is smaller. Writing instead of gives the ceiling (the smallest key ), and swapping left with right gives the predecessor and the floor.
In the tree built by inserting 50, 30, 70, 20, 40, 60, 80, what is the successor of 40, and which case finds it?
- 60, the smallest key in 50's right subtree
- 50: 40 has no right subtree, so climb until you arrive at a node from its left child, which first happens at 50
- 30, its parent
- 40 has no successor, because it is a leaf
Show the answer
B. 50: 40 has no right subtree, so climb until you arrive at a node from its left child, which first happens at 50
40 is the right child of 30, and 30 is the left child of 50. Climbing from 40, the first node reached from its left child is 50, and indeed 50 comes next in sorted order: 20, 30, 40, 50, 60, 70, 80.
Deletion: three cases
To delete a key, first find its node . Then:
- is a leaf: remove it.
- has one child: splice out, and the child takes its place.
- has two children: find its successor , the minimum of 's right subtree. Put 's key in 's place, then delete from the right subtree. Since is a minimum, it has no left child, so deleting it is case 1 or 2. This is Hibbard deletion (1962).
def delete(x, key): # returns the root of the updated subtree
if x is None:
return None
if key < x.key:
x.left = delete(x.left, key)
elif key > x.key:
x.right = delete(x.right, key)
elif x.left is None: # cases 1 and 2: at most one child
return x.right
elif x.right is None:
return x.left
else: # case 3: two children
s = x.right
while s.left is not None: # successor = minimum of the right subtree
s = s.left
x.key = s.key # copy it up, then remove it from below
x.right = delete(x.right, s.key)
return xCopying the successor's key up is the short version. Libraries move the successor's node into place instead (CLRS's TRANSPLANT), so that iterators and the data attached to each key stay valid.
Cases 1 and 2. Splicing out moves its child's subtree up one level. Every key in that subtree was already inside the interval of keys allowed below , so it is still on the correct side of every ancestor:
Case 3. Let and be the key sets of 's left and right subtrees. The successor is the minimum of , so it is larger than everything in and smaller than everything else in . It can sit in 's place:
The successor has no left child. A left child of would be a key of smaller than , contradicting . So removing is case 1 or 2, and the whole deletion walks at most two downward paths:
Height is everything
Search, minimum, maximum, successor, predecessor, insertion and deletion all walk down (and possibly back up) one path, so every operation costs . For keys the height can be anything from , for a complete tree, to , for a path, and the insertion order alone decides which.
Think first Build that path with keys inserted in increasing order. How many key comparisons does the construction make in total?
Key lands at depth after being compared with all earlier keys, so the total is : . That is exactly the comparison count of quicksort with a first-element pivot on sorted input, and the coincidence is no accident.
Now insert the keys in a uniformly random order. The first key becomes the root and splits the others into those that go left and those that go right, and each side is again built in random order: this is quicksort with the first element as the pivot. When a key is inserted it is compared with each of its ancestors, which are exactly the pivots of the ranges that contained it. So the total number of comparisons, the sum of all depths, equals quicksort's comparison count.
Label the keys by rank. Key becomes an ancestor of key exactly when is inserted first among the keys between them, inclusive: until then all of them follow the same search path, and the first one to arrive separates the rest. Each of the keys is equally likely to be first:
Sum over ordered pairs, grouping them by the distance , which occurs for ordered pairs:
Divide by , using :
A random BST holds keys. What is the expected average depth of a key? (A complete tree with 1000 keys averages about 8.0.)
Show the answer
11
, so : about 38% deeper than the complete tree's 7.99, and nowhere near the 499.5 of the sorted-input path. In simulations the height of such trees is typically around 20: the deepest key sits about twice as deep as an average one.
Recognizing it
A search tree, in practice your library's balanced one, is the tool when a problem needs order and change at the same time:
- "the smallest value greater than ", "the closest value to ", floor and ceiling, predecessor and successor;
- insertions and deletions interleaved with those questions, online, with and around to , so that per operation fits and does not;
- intervals that must not overlap, or events kept in time order while some are cancelled;
- "the -th smallest" or "how many are below " under updates, which needs an augmented tree.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Accept a booking only if it overlaps no accepted booking | Ordered map keyed by start: check the predecessor's end and the successor's start | per booking |
| Is there with and ? | Sliding window of values in an ordered set; one ceiling query per element | |
| For each element, the closest value among the earlier ones | Insert as you go; compare the floor and the ceiling | |
| The -th smallest key of a given BST | Inorder walk that stops after keys | |
| For each element, how many smaller ones lie to its right | Order statistics (an augmented tree), or a Fenwick tree over compressed values |
#include <set>
#include <vector>
using namespace std;
// Is there i < j with j - i <= k and |a[i] - a[j]| <= t ?
bool nearbyAlmostDuplicate(const vector<long long>& a, int k, long long t) {
set<long long> window; // values of the last k elements
for (int j = 0; j < (int)a.size(); ++j) {
auto it = window.lower_bound(a[j] - t); // ceiling of a[j] - t: O(log k)
if (it != window.end() && *it <= a[j] + t) return true;
window.insert(a[j]);
if (j >= k) window.erase(a[j - k]); // slide: keep indices j-k+1 .. j
}
return false;
}The contest idiom: lower_bound(x) is the ceiling, the smallest element . A plain set suffices here because a duplicate value inside the window is reported before it could be inserted twice. The values are 64-bit, so cannot overflow for 32-bit inputs.
| Language | Ceiling (smallest ) | Floor (largest ) | Notes |
|---|---|---|---|
C++ std::set, std::map | s.lower_bound(x) | prev(s.upper_bound(x)), unless it is begin() | Red-black trees in libstdc++, libc++ and MSVC; multiset for duplicates |
Java TreeSet, TreeMap | ceiling(x), ceilingKey(x) | floor(x), floorKey(x) | Red-black trees; higher and lower are the strict versions |
| Python | bisect_left on a sorted list | bisect_right minus 1 | No built-in ordered set: insertion into a list is . The third-party sortedcontainers keeps a list of sorted sublists, not a tree |
end(), null, or an index equal to the length.You must process operations in any order: insert a price, delete a price, and report the smallest stored price . Which structure fits?
- A hash set
- A binary heap
- A balanced BST, such as
std::set - A sorted array with binary search
Show the answer
C. A balanced BST, such as std::set
Ceiling queries need order, and the set changes between queries, so you need an ordered set with insertion, deletion and ceiling: about steps in all.
Key takeaways
- The BST property is about whole subtrees: smaller keys to the left, larger to the right. Inorder traversal therefore lists the keys in sorted order.
- Search, minimum, maximum, successor, predecessor, floor, ceiling, insertion and deletion each follow one root-to-leaf path: time.
- Deleting a node with two children moves in its successor, which has no left child, so every deletion reduces to splicing out a node with at most one child.
- The height ranges from to . Sorted input builds a path in time; random orders give average depth , an average over inputs, not a guarantee.
- Problems that mix order questions (successor, floor, ceiling, -th) with insertions and deletions call for the library's ordered set; membership alone calls for a hash set, and repeated minimums for a heap.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Deleting a node that has two children replaces it with its successor . Why can always be removed from its old position by one of the easy cases?
- is always a leaf
- is the root of 's right subtree
- has no left child, since a left child would be a smaller key in 's right subtree
- The BST property forbids left children inside a right subtree
Show the answer
C. has no left child, since a left child would be a smaller key in 's right subtree
is the minimum of 's right subtree. A left child of would also lie in that subtree and be smaller than , a contradiction. So has at most a right child, and removing it is case 1 or case 2.
You insert keys in increasing order into an empty plain BST, then search for each key once. What is the total cost?
- , since BST operations are logarithmic
- : the tree is a path, so each phase makes about comparisons
- : each new key is attached right next to the previous one
- expected, because the tree rebalances itself
Show the answer
B. : the tree is a path, so each phase makes about comparisons
The -th key is compared with all earlier keys on its way down, so the insertions make comparisons, and searching for key afterwards takes comparisons: in total.
Random insertion orders give an average depth of about . What does that guarantee for an application whose keys arrive as increasing timestamps?
- Nothing: it is an average over insertion orders, and increasing timestamps are the worst order
- expected time per operation, because the expectation covers every input
- amortized time per operation
- Height with high probability
Show the answer
A. Nothing: it is an average over insertion orders, and increasing timestamps are the worst order
An average-case bound averages over inputs. Timestamps arrive sorted, the tree becomes a path, and each operation costs . Treaps (expected time over the algorithm's own coin flips) and balanced trees (worst-case height) are the two cures.
In the tree built from 50, 30, 70, 20, 40, 60, 80, a ceiling query asks for the smallest key . Which nodes does the downward walk visit, and what does it return?
- 50, 70, 60; it returns 60
- 50, 30, 40; it returns 40
- 50, 30, 40; it returns 50
- All seven nodes; it returns 50
Show the answer
C. 50, 30, 40; it returns 50
At 50: , so record 50 and go left. At 30: , go right. At 40: , go right, and fall off the tree. The last recorded candidate, 50, is the answer, found by visiting three nodes.
Which task needs an ordered structure such as a balanced BST rather than a hash table?
- Counting the distinct words in a document
- Checking whether a username is already taken
- Grouping words that are anagrams of each other
- Listing the events with timestamps in while events are added and cancelled
Show the answer
D. Listing the events with timestamps in while events are added and cancelled
A range query needs the keys in order: find the ceiling of , then follow successors until you pass , time for results in a balanced tree. A hash table scatters neighboring keys and would have to scan everything.
Go deeper
- Random BSTs & Treaps · Expected depth about 2 ln n, and random priorities that keep a tree balanced.
- Augmented Search Trees · Subtree sizes for order statistics, interval trees and implicit keys.
- Splay Trees & Dynamic Optimality · Self-adjusting trees, the access lemma and a 40-year-old conjecture.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 12.
- D. E. Knuth, The Art of Computer Programming, vol. 3: Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 6.2.2.
- T. N. Hibbard, "Some combinatorial properties of certain trees with applications to searching and sorting," Journal of the ACM 9(1) (1962), 13–28.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 3.2.