A plain binary search tree can degrade to a O(n) chain if keys arrive in sorted order. Balanced trees like AVL and red-black fix this with intricate rebalancing rules. A treap takes a wonderfully lazy shortcut: give every node a random priority and require the tree to be a heap on those priorities as well as a BST on the keys (hence tree + heap = “treap”). Because the shape is now determined by the random priorities — not by the order keys were inserted — the tree is balanced in expectation, with height O(log n), using only simple rotations. Insert keys and watch random priorities rotate the tree into balance.
O(log n) expected height · BST on keys + max-heap on random priorities · rotations only
BST property
Keys obey binary-search order: left subtree < node < right subtree.
heap property
Priorities obey a max-heap: every node’s priority ≥ its children’s.
random priority
Each node gets a random priority on insertion — this decides the shape.
rotation
A local restructuring that fixes the heap property while preserving BST order.
treap.js — keys ordered, priorities heaped
Ready
Each node shows its key (top) and random priority (bottom). The tree is a BST on keys and a max-heap on priorities. Inserting a key places it by BST order, then rotates it up while its priority beats its parent’s. Insert to build.
0
nodes
0
height
–
last rotations
How it works
The trick is that a treap’s shape is uniquely determined by its set of (key, priority) pairs, regardless of insertion order — the BST-on-keys and heap-on-priorities constraints together leave exactly one valid tree. So if the priorities are random, the tree you get is the same as if you had inserted the keys in a random order, which is known to produce an expected height of O(log n). Insertion is simple: place the new key as a normal BST leaf, then, while it has a higher priority than its parent, rotate it upward — each rotation preserves the BST order but lifts the high-priority node toward the root, restoring the heap property. Deletion is the mirror: rotate the node down until it’s a leaf, then snip it.
1
Give each node a random priority
On insertion, assign the new key a random priority. The tree must satisfy BST order on keys and max-heap order on priorities simultaneously.
2
Insert as a BST leaf
Descend by key comparisons and attach the new node as a leaf, exactly as in an ordinary BST. This keeps the BST property but may violate the heap property.
3
Rotate up to fix the heap
While the new node’s priority exceeds its parent’s, rotate it up. Each rotation is a local restructuring that preserves BST order while moving the higher priority toward the root.
✓
Balanced in expectation
Because random priorities make the shape equivalent to random-order insertion, the expected height is O(log n). No AVL/red-black-style rules are needed — just rotations driven by priorities.
Height
O(log n) expected
Insert / delete
O(log n)
Rebalance
rotations only
Also called
randomized BST
The code
# treap insertion: BST on key, max-heap on random priorityimport random
def insert(t, key):
if t isNone: return Node(key, priority=random.random())
if key < t.key:
t.left = insert(t.left, key)
if t.left.priority > t.priority: # heap violated
t = rotate_right(t) # lift the child upelse:
t.right = insert(t.right, key)
if t.right.priority > t.priority:
t = rotate_left(t)
return t # rotations preserve BST order, fix the heap
Quick check
1. What two structures is a treap at the same time?
A treap is a "tree + heap": it maintains BST order on the keys and max-heap order on each node’s randomly assigned priority, both at once.
2. Why does a treap stay balanced without complex rebalancing rules?
The (key, priority) pairs determine a unique tree regardless of insertion order. Random priorities make that shape equivalent to random-order insertion, which has O(log n) expected height — no AVL/red-black rules needed.
3. How is the heap property restored after inserting a key?
The new node is placed as a BST leaf, then rotated upward as long as its priority beats its parent’s. Rotations are local restructurings that preserve BST order while lifting the higher priority toward the root.
FAQ
What is a treap?
A randomized balanced BST that is at once a binary search tree on its keys and a max-heap on a random priority per node. Since its shape comes from the random priorities, not insertion order, it has O(log n) expected height and supports insert/delete/search in O(log n) expected time with only simple rotations.
How does a treap compare to AVL and red-black trees?
AVL and red-black trees guarantee worst-case O(log n) height via strict rules (more complex code). A treap only guarantees O(log n) in expectation, but it’s far simpler and supports split/merge easily — a popular choice when simplicity and those operations matter more than a worst-case bound.
What are split and merge on a treap?
Split divides a treap into two by a key (smaller keys in one, rest in the other); merge combines two treaps (all keys in one < all in the other) into one. Both are O(log n), and they make implicit-key treaps behave like arrays with fast range insert/erase/reverse.
What happens if two nodes get the same priority?
Priority ties can blur the unique shape and slightly hurt balance, but with wide-range random priorities (32–64 bits) collisions are negligible; implementations either rely on that or break ties deterministically. In practice it’s a non-issue.
The picture: sorted left to right, heaped top to bottom
The page’s keys with fixed priorities. Reading left to right gives 10, 20, 30, 40, 45, 50, 60, 70, 80 (binary search tree order); reading any parent-to-child step shows a smaller priority (heap order). The highest priority, 94 on key 40, is the root, even though 40 was inserted fifth.
Worked example, step by step
Keys are inserted in the order 50, 30, 70, 20, 40, 60, 80, 10, 45, with priorities fixed in advance as 50→61, 30→83, 70→26, 20→53, 40→94, 60→91, 80→25, 10→88, 45→42. Each insert descends as in a binary search tree, then rotates the new node up while its priority beats its parent’s. “Rotations” counts rotations done by that one insert.
Step
Priority
Rotations
Root after
Height after
insert 50
61
0
50 (priority 61)
1
insert 30
83
1
30 (priority 83)
2
insert 70
26
0
30 (priority 83)
3
insert 20
53
0
30 (priority 83)
3
insert 40
94
2
40 (priority 94)
3
insert 60
91
2
40 (priority 94)
3
insert 80
25
0
40 (priority 94)
4
insert 10
88
2
40 (priority 94)
4
insert 45
42
0
40 (priority 94)
4
again in sorted order, same priorities
—
5
40 (priority 94)
4
There were 7 rotations over 9 inserts. Insert 30 rotated once because 83 beats 61, so 30 became the root; inserting 40 (priority 94) rotated twice and took the root from 30. Later, 60 (priority 91) climbed to the right of 40 in two rotations. The last row is the real lesson (it used 5 rotations, a different path to the same tree): building the same tree from the keys in sorted order, with the same priorities, gives the identical shape. The final shape depends only on the set of (key, priority) pairs, never on arrival order, which is what lets random priorities stand in for a random insertion order. A plain binary search tree given sorted input would be a chain of height 9.
Complexity and trade-offs
Case
Time
Space
Why
Treap search, insert, delete
O(log n) expected, O(n) worst
O(n) plus one priority per node
Expected, not guaranteed: it depends on the priorities being random and independent of the keys.
Plain binary search tree, sorted input
O(n) per operation
O(n)
Sorted keys form a chain: 9 sorted keys have height 9. A treap on 100,000 sorted keys with random priorities measured height 38, with about 1 rotation per insert on average.
AVL or red-black tree
O(log n) worst case
O(n) plus a balance field or colour bit
Guaranteed bound, but the update rules have many cases. The treap trades the guarantee for a very short implementation.
Skip list
O(log n) expected
O(n) expected, several pointers per node
Also randomised. Simple, but pointer-heavy and not a tree.
Treap split and merge
O(log n) expected each
O(n)
Because shape follows priorities, cutting at a key and joining two treaps are as short as insert, and give range operations and sequences.
The cost of the randomness is variance: any single run can be unlucky. Across 9 keys inserted in sorted order with random priorities, one run reached height 6, where 4 would be perfect. At scale the constant is modest, 38 against a perfect 17 for 100,000 keys, and a treap does not rebalance eagerly, so updates are cheap. Choose it when short code and easy split and merge matter more than a hard worst-case bound.
Common mistakes
Using the key (or a counter) as the priority
Priorities must be independent of the keys. With priority equal to key, inserting 1..9 in order makes each new key the largest priority, so it rotates all the way to the root and the tree is a chain of height 9: no better than a plain tree.
Giving every node the same priority
With a strict “child greater than parent” test, no rotation ever fires. Inserting 1..9 with every priority 5 yields a chain of height 9. Draw priorities from a wide random range (or random floats) so ties are rare.
Rotating in the wrong direction
A new left child with a higher priority needs a right rotation of its parent. Using the left rotation instead reads the parent’s missing right child: inserting 50 with priority 10 and then 30 with priority 90 raises AttributeError in the natural implementation, because the rotation tries to lift None. When it does not crash, it breaks key order.
Expecting perfect balance
Expected height is logarithmic, not minimal. Keys 1..9 inserted with priorities 31, 76, 70, 17, 48, 78, 61, 81, 75 form a tree of height 6, while 9 nodes could fit in height 4. A test that asserts a tight height bound will fail on valid treaps.
Checking only one of the two orders
A treap is two invariants at once. A test that confirms the in-order keys are sorted proves nothing about priorities. Check both: in-order keys ascending, and every parent priority at least every child’s.
Where this shows up
Ordered sets and maps with little code
When you need insertion, deletion and rank queries but not a worst-case guarantee, a treap is a few dozen lines. It is a common choice in programming contests for that reason.
Sequences with cut and paste
Treated as an implicit-key tree (positions instead of keys), split and merge give cut, copy and reverse of a range in expected logarithmic time. Text and list structures are built this way.
Order statistics
Storing subtree sizes in each node lets you ask “what is the k-th smallest?” or “how many keys are below x?” without extra structures; rotations just need to update two sizes.
A model for randomised data structures
The argument that random priorities mimic random insertion order is the same idea behind randomised quicksort and skip lists. Learning it here transfers directly.
SOLVE IT YOURSELF
Solve it: balance a BST with random priorities
A treap is two structures in one node: a BST on the key, a heap on a random priority. Keep both invariants and the shape is whatever a random insertion order would have produced — balanced, with no balance factors or colours to track. Python or TypeScript.
YOUR TASK
Implement Treap with insert(key), search(key), delete(key), inorder() and height(). Priorities come from the supplied seeded generator. Duplicate inserts are ignored.
HINTS — 7 IDEAS
Insert like a plain BST first — walk down on key comparisons and hang the new node off a leaf.
That leaf placement can violate the heap: the new node may outrank its parent. Fix it by rotating it up, once per level, on the way back out of the recursion.
A right rotation at n makes n.left the new subtree root and n its right child. Keys stay ordered because you only ever move a subtree that was already on the correct side.
Delete is the mirror image: rotate the doomed node down, always promoting the higher-priority child, until it has at most one child — then splice it out.
Rotating toward the higher-priority child is what keeps the heap intact during deletion. Promoting the lower one would break it immediately.
The priorities are random, so the tree's shape is the shape of a random BST: expected height about 3·log₂ n, no rebalancing rules required.
Same seed means same tree every run — that is the only reason a randomized structure can be unit-tested at all.