Info & Theory
A treap is a randomized binary search tree named for
combining a tree with a heap, introduced by
Cecilia Aragon and Raimund Seidel in 1989. Every node stores a
key and an independently chosen random
priority.
Dual invariant
The tree is simultaneously a BST on keys — left subtree keys are smaller, right subtree keys are larger — and a max-heap on priorities — every node's priority is at least as large as its children's priorities.
Why expected O(log n)
Because priorities are drawn uniformly at random, the shape
that results from arranging nodes by priority is
distributionally identical to a BST built by inserting keys
in a uniformly random order. Random BSTs are a classical
result with expected height O(log n), so treaps
inherit that guarantee automatically — with no explicit
balancing rules at all.
Insertion
Insert the key with an ordinary recursive BST insert, landing it as a leaf, and assign it a fresh random priority. Then rotate the node up — right rotation if it is a left child, left rotation if it is a right child — as long as its priority exceeds its parent's, restoring the max-heap property.
Deletion
Locate the node by key. While it has two children,
rotate down: promote whichever child holds the higher
priority (treating the deleted node's own priority as
−∞), pushing the target node toward a leaf.
Once it has at most one child, splice it out directly.
No explicit balance bookkeeping
Unlike AVL or red-black trees, which track heights or color bits and apply deterministic case-by-case rebalancing after every update, a treap needs none of that — randomness alone keeps the expected height logarithmic.
Bonus: split & merge
Treaps also support elegant O(log n)
split and merge operations, which make them a
popular building block for ordered sets, ropes, and
persistent data structures.