Intermediate Topic 35 of 52 Data Structures
Treaps
Randomized trees combining BST order with heap priorities.
How it works
A treap combines a binary search tree on keys with a heap on randomly assigned priorities. Because the shape is determined by random priorities, the tree behaves like a randomly built BST with expected height O(log n). Insertion adds a node as a leaf and rotates it up until the heap property holds, and deletion rotates it down. Split and merge operations are especially elegant.
Step-by-step walkthrough
- Each node has a key ordered like a BST.
- It also has a random priority ordered like a max-heap.
- Keys left of the root are smaller.
- Keys to the right are bigger.
- Inserting then rotates the node up until heap order holds, keeping the tree balanced in expectation.
Where it is used
Ordered sets with split and merge for competitive programming, implicit treaps for sequence operations like reversing a subarray, and simple randomized balanced trees use treaps.
Common pitfall
Balance is only probabilistic, so a poor random source or duplicated priorities can cause deep trees. Priorities must be assigned once and kept. The extra priority field costs memory. Recursion depth is usually small, but an adversary who knows the random seed could degrade it.
Where it fits in the course
Treaps is topic 35 of 52 in Data Structures, rated Intermediate. It follows Splay Trees. The next topic is Sparse Tables.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Data Structures quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Data Structures quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Treaps?
Where do people use Treaps?
What is the most common mistake with Treaps?
What should I learn before this topic?
How can I practice it?
Is Treaps hard to learn?
How long does it take to learn Treaps?
Which topics are related to Treaps?
What should I study after Treaps?
Related topics
- Splay Trees (Data Structures)
- Sparse Tables (Data Structures)
- Bloom Filters (Data Structures)
- Suffix Arrays (Data Structures)