II · Trees, with shape

Treap

BST and heap, secretly the same tree.

The story

A treap (tree + heap) gives every node a random priority. The keys form a binary search tree; the priorities form a heap. Because priorities are random, the resulting tree shape mimics a random BST: depth O(log n) with high probability. Aragon and Seidel proved this; the construction is shockingly compact.

How it works

Insert: BST-insert by key, then rotate up while the priority is greater than the parent's. Delete: rotate down to a leaf, then remove. Split and merge by key fall out cleanly. The structure shines for "give me the order statistics of [a, b)" workloads.

Where it lives

Competitive programming (where the simplicity wins over AVL/RB). Some functional language libraries. Used as the underlying ordered map in some persistent data-structure libraries.

The key insight

Worst-case O(n) (if the random source is unlucky). The expected O(log n) bound holds across all inputs but the bound is over the random priority choice, not the input distribution.

Published