Treap
A treap is a randomized binary search tree that assigns independent random priorities to keys, simultaneously maintaining binary search tree ordering and heap ordering to guarantee O(log n) expected depth.
Treap (a portmanteau of tree and heap) is a randomized self-balancing binary search tree within computation and algorithms that maintains dynamic ordered sets in O(log n) expected time per search, insertion, deletion, split, and join operation. Introduced by Raimund Seidel and Cecilia R. Aragon in 1989 (and structurally isomorphic to the Cartesian tree defined by Jean Vuillemin in 1980), a treap assigns each inserted node x both a user-supplied comparable search key k(x) and an independent, uniformly distributed random priority p(x).
By enforcing the binary search tree invariant on keys (every left descendant has a smaller key and every right descendant has a larger key) together with the heap invariant on priorities (every child has a priority no larger than its parent in a max-treap), a treap ensures that its tree topology is uniquely determined whenever all keys and priorities are distinct. Specifically, the root of any subtree must be the node with the maximum priority, which partitions the remaining elements by key into left and right subtreesโthe exact recursive partition generated by inserting the keys into an unbalanced binary search tree in decreasing order of their random priorities. Because the priorities are chosen uniformly at random independent of the input key order, a treap transforms any adversarial sequence of insertions (such as pre-sorted keys) into a uniform random permutation, achieving O(log n) expected height with high probability without complex deterministic rebalancing cases.
Structural Uniqueness and Probabilistic Depth Analysis
Dual Tree-Heap Invariant and Cartesian Tree Isomorphism
Let S = {(k1, p1), (k2, p2), โฆ, (kn, pn)} be a set of n pairs with distinct keys ki and distinct priorities pi. A binary tree T storing S is a max-treap if, for every node u โ T:
- Binary Search Tree Property (Keys): For every node v in the left subtree of u, k(v) < k(u); for every node w in the right subtree of u, k(w) > k(u).
- Max-Heap Property (Priorities): For every child c of u, p(c) < p(u).
By induction on n, there exists a unique treap T(S) for any set S with distinct keys and priorities: the root of T(S) must be the unique element r = arg maxxโS p(x) by the heap property, the left subtree must store S< = {x โ S : k(x) < k(r)} by the binary search tree property, and the right subtree must store S> = {x โ S : k(x) > k(r)}. Consequently, the shape of a treap is history-independent: regardless of the sequence of insertions and deletions that produced the current set S, the treap's structure is identical to the binary search tree obtained by inserting the elements of S in decreasing order of priority.
Expected Depth and Rotation Count via Indicator Variables
Rank the n elements of S in increasing order of their keys as x1, x2, โฆ, xn with k(x1) < k(x2) < โฆ < k(xn), and define the indicator random variable Ai,j โ {0, 1} to equal 1 if and only if xi is a proper ancestor of xj in the treap. Under the random priority insertion equivalence (identical to the pivot selection analysis of Quicksort), xi is an ancestor of xj if and only if xi is assigned the highest priority among all elements in the contiguous key interval {xmin(i,j), โฆ, xmax(i,j)}. Because priorities are independent and identically distributed, each of the |i โ j| + 1 elements in that interval is equally likely to have the maximum priority:
By linearity of expectation, the expected depth of the j-th ranked key xj is the sum of ancestor probabilities over all i โ j:
where Hm = โr=1..m 1/r โ ln m + ฮณ is the m-th harmonic number. Furthermore, the expected number of tree rotations performed during any single insertion or deletion equals the expected sum of the right-spine length of the left subtree and the left-spine length of the right subtree of the affected node, which satisfies E[rotations] < 2.
Split, Merge, and Rotation-Based Operations
Split and Join Primitives
In modern functional and competitive programming, treaps are most often implemented using two non-rotational structural primitivesโSplit and Merge (Join)โeach running in O(log n) expected time:
- Split(T, k): Partitions a treap T into two treaps (L, R) such that L contains all nodes with keys โค k and R contains all nodes with keys > k. If k(root(T)) โค k, recursively split the right child of T into (L', R), attach L' as the new right child of root(T), and return (T, R); otherwise split the left child symmetrically.
- Merge(L, R): Given two treaps L and R where every key in L is strictly smaller than every key in R, combines them into a single treap. Compare p(root(L)) and p(root(R)): if p(root(L)) > p(root(R)), make root(L) the new root and recursively set its right child to Merge(L.right, R); otherwise make root(R) the new root and set its left child to Merge(L, R.left).
Using Split and Merge, inserting a new node x splits T at k(x) into (L, R) and returns Merge(Merge(L, x), R), while deleting k splits out the target key and merges the remaining left and right halves. Alternatively, rotation-based insertion inserts x as a leaf using standard binary search tree key comparisons and rotates x upward until p(x) โค p(parent(x)), while deletion rotates x downward toward the higher-priority child until it becomes a leaf and detaches it.
| Balanced Search Tree | Balancing Mechanism | Search / Insert / Delete | Split / Join Time | Extra Metadata per Node | ||
|---|---|---|---|---|---|---|
| Treap (Seidel & Aragon, 1989) | Random heap priorities | O(log n) expected (whp) | O(log n) expected | 32- or 64-bit random priority | ||
| RedโBlack Tree (1978) | 1-bit color invariants | O(log n) worst-case | O(log n) worst-case | 1 color bit | ||
| AVL Tree (1962) | Height balance | ฮh | โค 1 | O(log n) worst-case | O(log n) worst-case | 2-bit balance factor or height |
| Splay Tree (1985) | Zig-zig / zig-zag splaying | O(log n) amortized | O(log n) amortized | Zero extra bits | ||
| Skip List (Pugh, 1990) | Geometric random tower height | O(log n) expected (whp) | O(log n) expected | Variable forward pointer array |
Implicit Treaps, Persistence, and Parallel Set Operations
Implicit Treaps for Dynamic Sequence Manipulation
Replacing explicit keys with implicit array indices calculated dynamically from subtree sizes (size[u] = 1 + size[left(u)] + size[right(u)]) yields an implicit treap (or randomized rope). Because Split(T, pos) can cleave a sequence of n elements at any index pos in O(log n) expected time, an implicit treap supports inserting or deleting arbitrary substrings, cutting and pasting blocks, reversing any contiguous subarray [l, r] via lazy propagation flags, and querying range sums or range minimums in O(log n) expected time per operation.
Persistent and Parallel Set Algebra (Blelloch & Reid-Miller)
Because Split and Merge modify only the O(log n) nodes along a single root-to-leaf spine without parent pointers or bottom-up color flips, treaps are naturally suited for path-copying persistence in purely functional programming languages. Furthermore, Guy Blelloch and Margaret Reid-Miller (1998) demonstrated that two treaps of sizes m and n (with m โค n) can compute their set union, intersection, and difference in O(m log(n/m)) expected work and O(log n) parallel span by splitting the tree with the smaller root priority by the key of the larger root priority and recursing on the resulting left and right subtrees in parallel.
Frequently Asked Questions
How does a treap differ from a binary heap or a standard binary search tree?
A binary heap enforces only the heap ordering on a single key and stores elements in a complete binary tree array, supporting O(1) find-max and O(log n) extract-max but requiring O(n) time to search for an arbitrary key. A standard binary search tree enforces left-to-right key ordering for fast searches but can degenerate into an O(n) linked list when keys are inserted in sorted order. A treap stores two values per nodeโa search key ordered as a binary search tree and a random priority ordered as a heapโcombining logarithmic search by key with logarithmic tree height.
Can an attacker force a treap into O(n) worst-case height if they know the input keys?
If the treap generates priorities using a cryptographically or statistically independent pseudo-random number generator (PRNG) seeded at runtime and hidden from the external caller (oblivious adversary), no input key sequenceโsorted, reverse-sorted, or alternatingโcan degrade the expected O(log n) depth, because the priorities are independent of the keys. Only if an attacker can inspect internal priority values or predict a deterministic hash function p(x) = hash(k(x)) can they selectively insert colliding high-priority keys.
Why is the expected number of rotations per treap insertion strictly less than 2?
During a rotation-based insertion, a newly inserted leaf x rotates upward once for each ancestor on its search path whose priority is smaller than p(x). After insertion completes, the exact number of upward rotations performed equals the sum of the number of nodes on the right spine of x's left subtree and the left spine of x's right subtree. Averaged over the uniform random priority of xj, the expected spine lengths sum to 2 โ 1/j โ 1/(n โ j + 1) < 2, matching the constant amortized structural modification cost of redโblack trees and contrasting with the O(log n) rotations per access in a splay tree.
References
- Seidel, R., & Aragon, C. R. (1996). "Randomized search trees." Algorithmica, 16(4โ5), 464โ497 (preliminary version in FOCS 1989, 540โ545). https://doi.org/10.1007/BF01940876
- Vuillemin, J. (1980). "A unifying look at data structures." Communications of the ACM, 23(4), 229โ239. https://doi.org/10.1145/358841.358852
- Blelloch, G. E., & Reid-Miller, M. (1998). "Fast set operations using treaps." In Proceedings of the Tenth Annual ACM Symposium on Parallel Algorithms and Architectures (SPAA '98), 16โ26. https://doi.org/10.1145/277651.277660
- Motwani, R., & Raghavan, P. (1995). Randomized Algorithms (Section 8.2: Randomized Search Trees). Cambridge University Press. https://doi.org/10.1017/CBO9780511814075