Short answer: A treap is a binary search tree on keys and a heap on independently random priorities. Each node stores a key and a priority. The in-order walk is the key order, and every parent has a better priority than its children. Insert and delete are rotations that restore the heap order after an ordinary search-tree splice. With random priorities the expected height is O(log n), so search, insert, and delete are expected O(log n). The same rotations support split and merge in expected logarithmic time.
What the problem actually asks
A binary search tree needs a rule that prevents a sorted insert from forming a path. A random priority, chosen once per node and never changed, makes the tree the unique search tree that is also a heap on those priorities. That tree has the same shape, in expectation, as a random binary search tree, whose expected depth is logarithmic.
The implementation does not reshuffle the tree globally. An inserted leaf rotates up while its priority beats its parent. A deleted node rotates down toward the better-priority child until it is a leaf, then unlinks. Split and merge are the operations that make treaps useful beyond a dictionary: cut the tree into keys less than x and keys greater than x, or glue two trees when every key on the left is smaller than every key on the right.
What the algorithm guarantees
Expected time of search, insert, delete, split, and merge is O(log n) when priorities are independent and continuous, so ties have probability zero. Extra memory is a priority and two child pointers per node. The bound is expectation over the priorities, not over the key sequence. An adversary who sees the priorities and also gets to set them can build a path. The caller must draw the priorities and keep them hidden from that adversary.
A treap is not a heap of the keys. The minimum key is the leftmost node, not the root, unless it also drew the best priority. Confusing the two orders breaks either search or the rotation direction.
The working steps
- On insert, attach the key as a leaf in search-tree position with a fresh random priority. Rotate it up while it has a better priority than its parent. A left child that outranks its parent rotates right, and a right child rotates left.
- On delete, while the node has two children, rotate it down across the child with the better priority. When it has one child or none, unlink it.
- Split on key x by inserting x with a priority better than every node, so it splays to the root by the heap rotations, then detach its left and right subtrees and discard x.
- Merge two treaps whose keys are all ordered left-then-right by creating a dummy root and rotating it down until it unlinks, leaving the two trees combined.
- Use a 64-bit random priority so collisions are negligible, and define a tie break by key if a collision still occurs.
Expected logarithmic time needs random priorities drawn by the structure. It is not a worst-case bound. AVL and red-black trees provide the worst case without randomness. A treap that stores subtree sizes answers order statistics. A treap that stores lazy tags on intervals is an implicit-key treap, a different and common use of the same rotations.
Approaches that look simpler and fail
| Approach | Why it fails when the priority is the key |
|---|---|
| Use the key as the priority | The tree is a path, the heap on keys, and search is linear. The priority has to be an independent random value. |
| Rotate toward the root on access, as in a splay tree | A treap rotates only to restore the heap order of fixed priorities. Access does not change shape. |
| Merge two treaps whose key ranges overlap | The search-tree order cannot be repaired by heap rotations if a left key is greater than a right key. Merge requires separated ranges. |
| Promise O(log n) for every insertion order without randomness | Sorted keys with adversarial priorities degenerate. The expectation is over the random draw. |
Worst-case balance belongs to AVL or red-black trees. Access-driven amortized balance belongs to splay trees. A treap is the randomized tree whose split and merge fall out of the same rotations.
A working example
This Python fragment is a treap. The shape is a binary search tree on the keys and a heap on the independent priorities. Inserting (5, 2), (1, 9), (3, 4) puts key 1 at the root because its priority is best. It prints the inorder keys 1 3 5.
class N:
def __init__(self, key, pri):
self.key, self.pri = key, pri
self.left = self.right = None
def rot_right(y):
x = y.left
y.left = x.right
x.right = y
return x
def rot_left(x):
y = x.right
x.right = y.left
y.left = x
return y
def insert(n, key, pri):
if n is None:
return N(key, pri)
if key < n.key:
n.left = insert(n.left, key, pri)
if n.left.pri > n.pri:
n = rot_right(n)
else:
n.right = insert(n.right, key, pri)
if n.right.pri > n.pri:
n = rot_left(n)
return n
def inorder(n, out):
if n:
inorder(n.left, out)
out.append(n.key)
inorder(n.right, out)
root = None
for key, pri in ((5, 2), (1, 9), (3, 4)):
root = insert(root, key, pri)
order = []
inorder(root, order)
assert order == [1, 3, 5] and root.key == 1
print(*order)
Where it is used
A treap is a randomized binary search tree: heap priorities replace the balance rules. Implicit treaps, keyed by subtree size, are ropes for sequence edits. Production ordered maps are usually red-black trees, which do not need random bits.
When you can drop this algorithm
Drop a treap when a library ordered map is enough and split is not required. Keep it when expected logarithmic time is acceptable, randomness is available, and split or merge of key-ordered trees is part of the job.
Why this stays published
We publish this so a search for a treap returns the two orders, key in-order and random priority heap-order, and the expected log n height. A treap keeps search-tree order on keys and heap order on random priorities, which gives expected O(log n) search, insert, delete, split, and merge.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
