A binary search tree keeps things sorted: every left child has a smaller key, every right child has a larger one. But a plain BST is only as good as the order items arrive. Insert them in sorted order and you get a linked list, not a tree — every lookup now costs instead of .
To fix that, you need the tree to stay balanced. AVL trees and red-black trees do it with elaborate rotation rules and extra color or height bits on every node. Those algorithms work, but they are notoriously subtle to implement correctly.
A treap takes a completely different route. Give each node a second field called its priority — a uniformly random number drawn when the node is created. Now enforce two invariants simultaneously:
- BST property on keys: left subtree keys < node key < right subtree keys.
- Max-heap property on priorities: every parent has a higher priority than its children.
Aragon and Seidel proved in 1989 that these two rules together force the tree's shape to be the unique binary search tree consistent with both orderings — and because priorities are random, the expected height is .
No rotation counters, no color bits, no rebalancing passes. Randomness does the work.
Comments
Loading comments...