Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 ii is an ancestor of key jj with probability 1/(∣i−j∣+1)1/(|i-j|+1), and derive the expected depth Hk+Hn−k+1−2H_k+H_{n-k+1}-2 of the key of rank kk.
  • Bound the expected height by 3log⁡2n+O(1)3\log_2 n+O(1) 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 O(log⁡n)O(\log n) 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 O(log⁡n)O(\log n) time.

Random BSTs and the ancestor lemma

DerivationProof, and the expected depth of every key
  1. m=the first key inserted among {min⁡(i,j),…,max⁡(i,j)}m=\text{the first key inserted among }\{\min(i,j),\dots,\max(i,j)\}

    One path until they are separated. A key outside the range from min⁡(i,j)\min(i,j) to max⁡(i,j)\max(i,j) 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, mm, takes the node where that path ends:

  2. Pr⁡[ i is a proper ancestor of j ]=1∣i−j∣+1\Pr[\,i\text{ is a proper ancestor of }j\,]=\frac{1}{|i-j|+1}

    Then they part. Every other key of the range passes through mm's node. If m=im=i, then jj ends up below ii; if m=jm=j, the reverse; otherwise ii and jj go to different sides of mm, and neither is an ancestor of the other. Each of the ∣i−j∣+1|i-j|+1 keys is equally likely to be mm:

  3. E[depth⁡(k)]=∑i<k1k−i+1+∑i>k1i−k+1=(Hk−1)+(Hn−k+1−1)\E[\operatorname{depth}(k)]=\sum_{i<k}\frac{1}{k-i+1}+\sum_{i>k}\frac{1}{i-k+1}=\big(H_k-1\big)+\big(H_{n-k+1}-1\big)

    Depth of the key of rank kk, by linearity of expectation over its possible ancestors:

  4. 1n∑k=1nE[depth⁡(k)]=2(1+1n)Hn−4 ∼ 2ln⁡n\frac1n\sum_{k=1}^{n}\E[\operatorname{depth}(k)]=2\Big(1+\frac1n\Big)H_n-4\ \sim\ 2\ln n

    Averaged over all keys, using ∑k=1nHk=(n+1)Hn−n\sum_{k=1}^{n}H_k=(n+1)H_n-n, this is the formula of the Optimized lesson:

Every key's expected depth is at most 2Hn−2≤2ln⁡n2H_n-2\le2\ln n, and the extreme keys are the shallowest. The sum of all depths equals the number of comparisons quicksort makes with a first-element pivot, 2(n+1)Hn−4n≈1.39 nlog⁡2n2(n+1)H_n-4n\approx1.39\,n\log_2 n, because a key's ancestors are exactly the pivots it was compared with.

Predict before you look

In a random BST with n=50n=50 keys, what is the expected depth of the smallest key?

Show the answer

3.5

H1+H50−2=H50−1≈4.499−1=3.499H_1+H_{50}-2=H_{50}-1\approx4.499-1=3.499. 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 H50≈4.5H_{50}\approx4.5 record lows.

How tall is a random BST?

The height is the depth of the deepest key, a maximum of nn dependent random variables, and it is noticeably larger than the average depth. A neat argument bounds its expectation by studying 2height2^{\text{height}} instead of the height itself.

DerivationExpected height at most 3 log₂ n + O(1)
  1. Yn=2max⁡(YR−1, Yn−R)Y_n=2\max\big(Y_{R-1},\,Y_{n-R}\big)

    Let XnX_n be the height of a random BST with nn keys and Yn=2XnY_n=2^{X_n} its exponential height, with Y0=0Y_0=0 and Y1=1Y_1=1. If the root has rank RR, uniform on 1,…,n1,\dots,n, then for n≥2n\ge2

  2. E[Yn] ≤ 2n∑r=1n(E[Yr−1]+E[Yn−r])=4n∑i=0n−1E[Yi]\E[Y_n]\ \le\ \frac{2}{n}\sum_{r=1}^{n}\big(\E[Y_{r-1}]+\E[Y_{n-r}]\big)=\frac4n\sum_{i=0}^{n-1}\E[Y_i]

    Bound the maximum by the sum and average over RR; each subtree size ii appears twice:

  3. E[Yn] ≤ 14(n+33)=(n+1)(n+2)(n+3)24\E[Y_n]\ \le\ \frac14\binom{n+3}{3}=\frac{(n+1)(n+2)(n+3)}{24}

    By induction on nn, with the hockey-stick identity ∑i=0n−1(i+33)=(n+34)\sum_{i=0}^{n-1}\binom{i+3}{3}=\binom{n+3}{4} (the base cases Y0=0≤14Y_0=0\le\frac14 and Y1=1≤1Y_1=1\le1 hold):

  4. E[Xn] ≤ 3log⁡2n+O(1) ≈ 4.328ln⁡n\E[X_n]\ \le\ 3\log_2 n+O(1)\ \approx\ 4.328\ln n

    Since 2x2^x is convex, Jensen's inequality gives 2E[Xn]≤E[2Xn]=E[Yn]=O(n3)2^{\E[X_n]}\le\E[2^{X_n}]=\E[Y_n]=O(n^3), so

The elementary bound 3log⁡2n≈4.328ln⁡n3\log_2 n\approx4.328\ln n is within half a percent of the true constant 4.3114.311. 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 2.5log⁡2n2.5\log_2 n, 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 4.311ln⁡n4.311\ln n levels deep in expectation, and in the worst case n−1n-1, which is why careful implementations recurse on the smaller part and loop on the larger one, keeping the stack at O(log⁡n)O(\log n) 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 Hk+Hn−k+1−2H_k+H_{n-k+1}-2, expected height about 4.311ln⁡n4.311\ln n. 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.

DerivationFewer than two rotations per update, in expectation
  1. #rotations=C+D\#\text{rotations}=C+D

    Let the inserted key xx have rank kk among the nn keys after the insertion. Each rotation that lifts xx adds one node either to the right spine of xx'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 CC and DD:

  2. E[C]=∑d=1k−11d(d+1)=∑d=1k−1(1d−1d+1)=1−1k\E[C]=\sum_{d=1}^{k-1}\frac{1}{d(d+1)}=\sum_{d=1}^{k-1}\Big(\frac1d-\frac1{d+1}\Big)=1-\frac1k

    A key y<xy<x lies on that right spine exactly when, among the keys y,…,xy,\dots,x, the key xx has the smallest priority and yy the second smallest. For yy at distance dd below xx there are d+1d+1 such keys, so the probability is 1(d+1)d\frac{1}{(d+1)d}, and the sum telescopes:

  3. E[C+D]=2−1k−1n−k+1 < 2\E[C+D]=2-\frac1k-\frac{1}{n-k+1}\ <\ 2

    By symmetry E[D]=1−1n−k+1\E[D]=1-\frac{1}{n-k+1}, so

  4. E[time per update]=O(log⁡n),E[rotations per update]<2\E[\text{time per update}]=O(\log n),\qquad \E[\text{rotations per update}]<2

    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, O(log⁡n)O(\log n) in expectation:

Split, merge and implicit treaps

Two operations do most of the work. split(t, k) cuts a treap into the keys <k<k and the keys ≥k\ge k by walking one search path and re-hanging the pieces on the way back. merge(a, b), for treaps in which every key of aa precedes every key of bb, keeps whichever root has the smaller priority on top and merges the rest into its inner side, walking down the right spine of aa and the left spine of bb. Both take expected O(log⁡n)O(\log n) 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.

python
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 t

Equal 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 kk elements" from the rest compares kk with subtree sizes on the way down, and every sequence operation becomes a few splits and merges in expected O(log⁡n)O(\log n) 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.

cpp
#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 [l,r)[l, r), 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.

Check your understanding

reverseRange splits off the block, flips one flag and merges back, touching O(log⁡n)O(\log n) nodes even when the block holds a million elements. Why is flipping one flag enough?

  1. 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, O(1)O(1) per visited node
  2. Treaps store every block in reverse order anyway
  3. Reversing a sequence does not change its inorder traversal
  4. 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, O(1)O(1) 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 ii is an ancestor of key jj with probability 1/(∣i−j∣+1)1/(|i-j|+1); the key of rank kk has expected depth Hk+Hn−k+1−2H_k+H_{n-k+1}-2, and the sum of all depths is quicksort's comparison count.
  • The exponential-height argument bounds the expected height by 3log⁡2n+O(1)≈4.33ln⁡n3\log_2 n+O(1)\approx4.33\ln n, close to the truth: αln⁡n−βln⁡ln⁡n+O(1)\alpha\ln n-\beta\ln\ln n+O(1) with α≈4.311\alpha\approx4.311 and O(1)O(1) 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 O(log⁡n)O(\log n) 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 O(log⁡n)O(\log n) time.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In a random BST on the keys 1,…,1001,\dots,100, what is the probability that key 10 is an ancestor of key 20?

  1. 1/101/10
  2. 1/111/11
  3. 1/21/2
  4. 1/1001/100
Show the answer

B. 1/111/11

Key 10 must be inserted first among the 11 keys 10,11,…,2010,11,\dots,20, and each of them is equally likely to come first.

Question 2

A treap receives the keys 1,2,…,n1,2,\dots,n in increasing order. What is the expected depth of a key?

  1. Θ(n)\Theta(n), since sorted input is the worst case for BSTs
  2. O(log⁡n)O(\log n): the shape depends only on the random priorities, so it is a random BST whatever the insertion order
  3. O(1)O(1), because each new key is rotated up to the root
  4. It depends on the priority drawn for key 1
Show the answer

B. O(log⁡n)O(\log n): 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 Hk+Hn−k+1−2=O(log⁡n)H_k+H_{n-k+1}-2=O(\log n).

Question 3

Why does a treap insertion make fewer than 2 rotations in expectation?

  1. Each rotation adds a node to one of two spines below the new key, and their expected lengths are 1−1/k1-1/k and 1−1/(n−k+1)1-1/(n-k+1)
  2. New keys always start at depth at most 2
  3. A new key always reaches the root within two rotations
  4. 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 1−1/k1-1/k and 1−1/(n−k+1)1-1/(n-k+1)

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 dd lies on such a spine with probability 1/(d(d+1))1/(d(d+1)), and these probabilities telescope to 1−1/k1-1/k and 1−1/(n−k+1)1-1/(n-k+1).

Question 4

In an implicit treap storing a sequence, what plays the role of the key when split descends the tree?

  1. The element's value
  2. Its position, computed on the way down from subtree sizes
  3. Its random priority
  4. 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 kk 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.