Random BSTs & Treaps
Expected depth about 2 ln n, and random priorities that keep a tree balanced.
Quicksort and binary search trees are one algorithm in disguise: building a BST from a random order makes exactly the comparisons quicksort makes. A treap stops hoping for a random input and flips its own coins instead. Every key gets a random priority, and the tree takes the shape it would have had if the keys had arrived in random order, whatever order they actually came in.
What you’ll learn
- Prove that in a random BST key is an ancestor of key with probability , and derive the expected depth of the key of rank .
- Bound the expected height by with the exponential-height argument, and state the sharp results of Devroye and Reed.
- Define treaps, prove that keys and priorities determine the tree uniquely, and show expected time per operation with fewer than 2 expected rotations per update.
- Implement split and merge, and use implicit treaps, indexed by position, to reverse a block of a sequence in expected time.
Random BSTs and the ancestor lemma
One path until they are separated. A key outside the range from to compares the same way with every key inside it. So until some key of the range is inserted, all of them would follow the same search path, and the first one inserted, , takes the node where that path ends:
Then they part. Every other key of the range passes through 's node. If , then ends up below ; if , the reverse; otherwise and go to different sides of , and neither is an ancestor of the other. Each of the keys is equally likely to be :
Depth of the key of rank , by linearity of expectation over its possible ancestors:
Averaged over all keys, using , this is the formula of the Optimized lesson:
Every key's expected depth is at most , and the extreme keys are the shallowest. The sum of all depths equals the number of comparisons quicksort makes with a first-element pivot, , because a key's ancestors are exactly the pivots it was compared with.
In a random BST with keys, what is the expected depth of the smallest key?
Show the answer
3.5
. The proper ancestors of the minimum are the record lows of the insertion order, the keys smaller than everything inserted before them, except the minimum itself; a random order of 50 keys has on average record lows.
How tall is a random BST?
The height is the depth of the deepest key, a maximum of dependent random variables, and it is noticeably larger than the average depth. A neat argument bounds its expectation by studying instead of the height itself.
Let be the height of a random BST with keys and its exponential height, with and . If the root has rank , uniform on , then for
Bound the maximum by the sum and average over ; each subtree size appears twice:
By induction on , with the hockey-stick identity (the base cases and hold):
Since is convex, Jensen's inequality gives , so
The elementary bound is within half a percent of the true constant . In numbers: simulated random BSTs with a million keys have an average depth of about 25 and a height between about 45 and 52, roughly , while a complete tree would have height 19.
Think first The sum of the depths in a random BST is quicksort's comparison count. What does its height correspond to in quicksort?
The depth of quicksort's recursion, the longest chain of nested partitions: the tree of pivots is a random BST. Randomized quicksort therefore recurses about levels deep in expectation, and in the worst case , which is why careful implementations recurse on the smaller part and loop on the larger one, keeping the stack at for every input.
Treaps: randomness you control
Random priorities make the priority order a uniformly random permutation, so a treap is a random BST, after every sequence of insertions and deletions, provided the sequence does not depend on the priorities. Everything above now holds as expected time over the algorithm's own coins, for every input: expected depth , expected height about . Sorted input no longer hurts.
Insertion places the key as a new leaf, as in a plain BST, then rotates it up while its priority is smaller than its parent's. Deletion rotates the key down, each time lifting the child with the smaller priority, until it has at most one child, and then splices it out. Both end in the unique shape.
Let the inserted key have rank among the keys after the insertion. Each rotation that lifts adds one node either to the right spine of 's left subtree (the path from its root that always goes right) or to the left spine of its right subtree. Call their final lengths and :
A key lies on that right spine exactly when, among the keys , the key has the smallest priority and the second smallest. For at distance below there are such keys, so the probability is , and the sum telescopes:
By symmetry , so
A deletion performs the same rotations in reverse, so it also makes fewer than 2 in expectation. The search part of an update still costs the depth, in expectation:
Split, merge and implicit treaps
Two operations do most of the work. split(t, k) cuts a treap into the keys and the keys by walking one search path and re-hanging the pieces on the way back. merge(a, b), for treaps in which every key of precedes every key of , keeps whichever root has the smaller priority on top and merges the rest into its inner side, walking down the right spine of and the left spine of . Both take expected time, and the result is again the unique treap of its keys.
Insertion becomes one split and two merges; deletion replaces a node by the merge of its two subtrees.
import random
class Node:
__slots__ = ('key', 'pri', 'left', 'right')
def __init__(self, key):
self.key, self.pri = key, random.random() # smaller priority sits higher
self.left = self.right = None
def split(t, key): # -> (keys < key, keys >= key), expected O(log n)
if t is None:
return None, None
if t.key < key:
t.right, b = split(t.right, key)
return t, b
a, t.left = split(t.left, key)
return a, t
def merge(a, b): # every key of a precedes every key of b
if a is None or b is None:
return a or b
if a.pri < b.pri: # a's root wins the heap order and stays on top
a.right = merge(a.right, b)
return a
b.left = merge(a, b.left)
return b
def insert(t, key):
a, b = split(t, key)
return merge(merge(a, Node(key)), b)
def erase(t, key): # remove one copy of key
if t is None:
return None
if t.key == key:
return merge(t.left, t.right)
if key < t.key: t.left = erase(t.left, key)
else: t.right = erase(t.right, key)
return tEqual keys go to the right part of a split, so this treap is a multiset: inserting a key twice stores it twice, and erase removes one copy. Set union, intersection and difference follow from split and merge too.
An implicit treap drops the keys altogether. Its nodes are ordered by position in a sequence, and each node stores the size of its subtree, so a node's position is the size of its left subtree plus everything to the left of that subtree. Splitting "the first elements" from the rest compares with subtree sizes on the way down, and every sequence operation becomes a few splits and merges in expected time: insert or delete at a position, cut a block and paste it elsewhere, and sum or minimum over a block if nodes also store their subtree's aggregate.
Reversing a block uses a lazy flag: mark the block's root "mirrored" and let each node swap its children only when a later operation first visits it.
#include <random>
#include <utility>
using namespace std;
mt19937 rng(2024);
struct Node {
int val, size = 1;
unsigned pri; // random priority: smaller sits higher
bool rev = false; // "reverse my subtree" is pending
Node *l = nullptr, *r = nullptr;
explicit Node(int v) : val(v), pri(rng()) {}
};
int sz(Node* t) { return t ? t->size : 0; }
void pull(Node* t) { t->size = 1 + sz(t->l) + sz(t->r); }
void push(Node* t) { // hand a pending reversal to the children
if (t && t->rev) {
swap(t->l, t->r);
if (t->l) t->l->rev ^= true;
if (t->r) t->r->rev ^= true;
t->rev = false;
}
}
void split(Node* t, int k, Node*& a, Node*& b) { // first k elements -> a
if (!t) { a = b = nullptr; return; }
push(t);
if (sz(t->l) < k) { split(t->r, k - sz(t->l) - 1, t->r, b); a = t; }
else { split(t->l, k, a, t->l); b = t; }
pull(t);
}
Node* merge(Node* a, Node* b) {
if (!a || !b) return a ? a : b;
if (a->pri < b->pri) { push(a); a->r = merge(a->r, b); pull(a); return a; }
push(b); b->l = merge(a, b->l); pull(b); return b;
}
Node* reverseRange(Node* t, int l, int r) { // reverse positions [l, r)
Node *a, *b, *c;
split(t, l, a, b);
split(b, r - l, b, c);
if (b) b->rev ^= true; // O(1): the work is deferred
return merge(merge(a, b), c);
}The contest "rope": half-open block , 0-indexed. Building the sequence is a merge per element, and reading it back is an inorder walk that pushes flags down as it goes. Tested against a brute-force reversal of random blocks.
reverseRange splits off the block, flips one flag and merges back, touching nodes even when the block holds a million elements. Why is flipping one flag enough?
- The flag means "this subtree is mirrored": each node swaps its children when a later split, merge or walk first visits it, so the reversal is paid for lazily, per visited node
- Treaps store every block in reverse order anyway
- Reversing a sequence does not change its inorder traversal
- After the splits, the block's nodes are all leaves, so there is nothing to swap
Show the answer
A. The flag means "this subtree is mirrored": each node swaps its children when a later split, merge or walk first visits it, so the reversal is paid for lazily, per visited node
Mirroring a subtree reverses its inorder sequence. The flag records that the mirror is owed; push performs it one node at a time, exactly when an operation needs that node's children to be correct.
Key takeaways
- In a random BST, key is an ancestor of key with probability ; the key of rank has expected depth , and the sum of all depths is quicksort's comparison count.
- The exponential-height argument bounds the expected height by , close to the truth: with and variance (Devroye; Reed).
- A treap is the unique tree that is a BST on keys and a heap on priorities. Random priorities make it a random BST for every input: expected time per operation and fewer than 2 expected rotations per update.
- Split and merge make treaps a toolkit, and implicit treaps index by position through subtree sizes, supporting lazy block reversals and range aggregates in expected time.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In a random BST on the keys , what is the probability that key 10 is an ancestor of key 20?
Show the answer
B.
Key 10 must be inserted first among the 11 keys , and each of them is equally likely to come first.
A treap receives the keys in increasing order. What is the expected depth of a key?
- , since sorted input is the worst case for BSTs
- : the shape depends only on the random priorities, so it is a random BST whatever the insertion order
- , because each new key is rotated up to the root
- It depends on the priority drawn for key 1
Show the answer
B. : the shape depends only on the random priorities, so it is a random BST whatever the insertion order
A treap's shape is the BST built by inserting the keys in priority order, and random priorities make that order uniformly random. The insertion order of the keys is irrelevant, so each key's expected depth is .
Why does a treap insertion make fewer than 2 rotations in expectation?
- Each rotation adds a node to one of two spines below the new key, and their expected lengths are and
- New keys always start at depth at most 2
- A new key always reaches the root within two rotations
- Priorities are sorted, so no key ever rotates twice
Show the answer
A. Each rotation adds a node to one of two spines below the new key, and their expected lengths are and
After the insertion, the rotations performed equal the lengths of the right spine of the new key's left subtree plus the left spine of its right subtree. A key at distance lies on such a spine with probability , and these probabilities telescope to and .
In an implicit treap storing a sequence, what plays the role of the key when split descends the tree?
- The element's value
- Its position, computed on the way down from subtree sizes
- Its random priority
- The depth of its node
Show the answer
B. Its position, computed on the way down from subtree sizes
An implicit treap stores no keys. The position of a node is the size of its left subtree plus the number of elements to the left of the current subtree, so split(t, k) compares with size(left) at each node, exactly like an order-statistic search.
Further reading
- R. Seidel & C. R. Aragon, "Randomized search trees," Algorithmica 16 (1996), 464–497; first presented by Aragon & Seidel at FOCS 1989.
- L. Devroye, "A note on the height of binary search trees," Journal of the ACM 33(3) (1986), 489–498.
- B. Reed, "The height of a random binary search tree," Journal of the ACM 50(3) (2003), 306–332.
- C. Martínez & S. Roura, "Randomized binary search trees," Journal of the ACM 45(2) (1998), 288–323.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 12 and the treap problem of chapter 13.