Learn
Lesson · Randomised Algorithms · Randomness inside the structure

Treaps

A search tree's shape is decided by the insertion order, which the structure does not control. A treap gives every key a random priority and keeps heap order on the priorities as well as search order on the keys; the resulting tree is unique, so the insertion order cannot reach it. Twelve keys inserted in sorted order give a plain tree of height 11 and a treap of height 5, and inserting the same keys and priorities in a shuffled order gives the same treap, node for node.

a treap is a search tree on the keys AND a heap on the priorities for distinct keys and distinct priorities that tree is UNIQUE so the insertion order cannot change it — only the priorities can twelve keys sorted: plain tree height 11, treap height 5 mean depth 5/2, counted; 2 ln n reads 4.970 and is an ASYMPTOTE rotations restore heap order only: there is no balance invariant anywhere
Two orders at once, and the uniqueness that follows

Core ideas

What this lesson establishes

The hard idea is the uniqueness, because everything else follows from it. The other two are where the randomness comes from and what the structure does not have.

1

Two invariants at once, and they determine the tree

A treap holds a key and a priority at each node, is a binary search tree on the keys, and is a min-heap on the priorities. If all the keys and all the priorities are distinct, exactly one such tree exists: the minimum priority must be at the root, the keys below it split by the search property, and the same argument applies recursively. The lab's opening instance has the key with priority 1 at the root, and there is nothing to choose.

2

Uniqueness makes the insertion order irrelevant

Two different insertion orders of the same key–priority pairs must end at the same tree, because there is only one tree they could end at. The panel builds it twice — sorted on the left, a shuffle on the right — and reports the same tree, node for node, while the rotation counts differ, 8 against 11. Different work, identical result.

3

The shape is the shape of a randomly built tree, and there is no balance rule

A treap on keys with priorities in random order is exactly the tree a plain search tree would have if the keys had arrived in the order of those priorities. So its expected depth is the expected depth of a randomly built search tree, which The Shape Problem and Random BSTs measured: 2 ln n asymptotically. Nothing checks a height, nothing checks a balance factor, and the rotations here restore heap order only.

The material

A random order the structure supplies itself

The two invariants, the uniqueness proof, what insertion costs, and the honest status of the depth figure.

Binary Search Trees showed a tree's cost depending on something the structure does not choose: twelve keys arriving in sorted order give a path of height 11, and the same twelve arriving shuffled give a height of 4. Rotations and the AVL Invariant fixed that by adding a rule the structure enforces on every insertion. This lesson fixes it differently — by making the shape depend on coins instead of on the arrival order.

Definition · A treap

A treap is a binary tree in which each node holds a key and a priority. It satisfies the search property on the keys — every key in a left subtree is smaller, every key in a right subtree is larger — and the heap property on the priorities: every node's priority is smaller than its children's.

Theorem · Uniqueness

For any finite set of pairs with distinct keys and distinct priorities, exactly one treap contains them.

Induct on the number of pairs. With none, the empty tree is the only one. Otherwise the heap property forces the pair with the smallest priority to be at the root: any other node with that pair would have an ancestor of larger priority.

The search property then forces the partition of the remaining pairs: every key smaller than the root's goes into the left subtree and every larger key into the right. Neither subtree has a choice about which pairs it contains.

Each subtree is itself a treap on a strictly smaller set with distinct keys and distinct priorities, so by induction each is unique. The whole tree is therefore unique.

□

The lab does not argue this, it checks it. Both panels are built from the same priority assignment and compared node for node, and the verdict reads the same tree, node for node or words that would refute the claim. Priorities are ranked rather than taken raw so that no two can collide; a tie would leave the shape undetermined and the claim would fail for a reason with nothing to do with treaps.

Example · Twelve keys, one priority assignment, two insertion orders

The keys are 10, 20, …, 120 and the seed assigns priorities 10:6 20:3 30:1 40:10 50:12 60:7 70:2 80:11 90:9 100:5 110:4 120:8. Priority 1 belongs to key 30, so 30 is the root. Inserting in sorted order costs 8 rotations; inserting in a shuffled order costs 11. Both produce a tree of height 5 with mean depth 5/2, and the two trees are identical. A plain search tree on the same sorted order has height 11 and mean depth 11/2.

Height 5 against 11, and mean depth 5/2 against 11/2: the treap is less than half as deep on average, on the input that is worst for a plain tree. And it got there without any rule about heights — the only thing being maintained is heap order on twelve numbers the structure generated itself.

Insertion, and what a rotation is for here

To insert a key, give it a random priority, place it as a leaf by the ordinary search-tree rule, and then rotate it upwards while its priority is smaller than its parent's. A rotation preserves the search property — Rotations and the AVL Invariant proves that, and the in-order sequence is what it preserves — so the search property is never in danger, and the loop stops exactly when heap order is restored.

That is the whole implementation, and it is worth noticing what is absent. No height is stored, no balance factor is computed, no case analysis over four shapes. Deletion is the same idea in reverse: rotate the node down until it is a leaf, then remove it. The panel's rotation counts, 8 and 11 for the two orders, are the only work the structure did beyond the searches.

What the guarantee is, and what the printed 2 ln n is not

The depth of a treap is a random variable, and its expectation is the expected depth of a search tree built from a uniformly random insertion order — which is 2 ln n + O(1) for the mean depth, and O(log n) for the height. Both of those are stated on this path: The Shape Problem and Random BSTs states them, Randomised Quicksort derives the recurrence they come from, because a random root and a random pivot are the same object, and no lesson in this library carries the full argument.

So the panel prints 2 ln n in its own row, labelled asymptotic, and it is about 15 per cent wrong about the tree in front of you. At n = 12 it reads 4.970 while the counted mean depth is 2.500 and the counted height is 5. Three numbers, three meanings: one asymptote, one exact mean of integers, one count. Reading them as estimates of each other is the failure mode of this page, and it is why each is labelled where it is printed.

The guarantee is also in expectation and not always. Over seeds 1 to 12 at twelve keys the treap's height came out 5, 6, 4, 5, 5, 6, 6, 5, 5, 4, 6, 5 — never 11, and never 3 either. Move the priority seed and watch it move. An AVL tree's height at twelve keys is bounded by a rule the structure enforces; a treap's is a random variable whose bad cases are unlikely rather than impossible.

That is the trade, and it is the same trade a random pivot makes. The input is arbitrary, possibly chosen by someone who wants the structure to perform badly, and the coins are the structure's own, so no input can be bad for it — only an unlucky draw can, and the draw is not the adversary's to make. Universal Hashing bought the same thing for a hash table with the same manoeuvre.

Interactive

Treaps: a random priority instead of a balance rule

The shape is the one a random insertion order would have built, whatever order you use

The same keys, the same priorities, two insertion ordersa search tree on the keys and a heap on the priorities, which fixes the shape
the first orderpriorities above each node

Method

Working with a structure that randomises itself

Find the root before anything else; the rest of the tree is forced.

1

Find the smallest priority: that is the root

Then partition the remaining keys by comparison with it and recurse. This is the uniqueness proof used as an algorithm, and it builds the tree without reference to any insertion order at all.

2

Change the insertion order and expect nothing to happen

Swap the two order menus. The rotation counts change and the trees do not. If they ever differed, the priorities would be the thing to check first — a tie breaks uniqueness and nothing else does.

3

Change the priority seed to see the real variability

This is the knob that matters. Heights at twelve keys range over 4, 5 and 6 across the first dozen seeds. That spread is the guarantee's actual content: bad shapes are unlikely, not impossible.

4

Keep the three depth numbers apart

The counted height, the exact mean depth as a fraction, and the 2 ln n asymptote. At twelve keys they are 5, 5/2 and 4.970. Only the first two are about this tree, and the panel labels all three.

Uniqueness and what follows from it

Score 0 / 0

One priority assignment, two insertion orders

Keys 10 to 120, priorities from the seed, and the claim that the insertion order cannot be read off the result.

key 10 20 30 40 50 60 70 80 90 100 110 120 priority 6 3 1 10 12 7 2 11 9 5 4 8 smallest priority is 1, at key 30, so 30 is the root left of 30: keys 10, 20 smallest priority there is 3, at key 20 right of 30: keys 40..120 smallest priority there is 2, at key 70 tree height mean depth rotations treap, inserted sorted 5 5/2 = 2.500 8 treap, inserted shuffled 5 5/2 = 2.500 11 the two trees identical, node for node plain search tree, inserted sorted 11 11/2 = 5.500 0 2 ln n at n = 12 - 4.970 asymptotic treap height at n = 12 over priority seeds 1..12 5 6 4 5 5 6 6 5 5 4 6 5 never 11, never 3

Build the top two levels from the priority row by hand before looking at the drawing: root 30, then 20 on the left and 70 on the right. Nothing about the insertion order entered that reasoning, which is exactly the claim — the priorities determine the tree and the order determines only the rotations.

The rotation counts are the one place the two runs differ, 8 against 11. That is real work and it is the price of the guarantee: a plain tree on the sorted order does no rotations at all and ends up with height 11. Paying eight rotations to halve the depth is the trade, and it is cheaper than the AVL case analysis it replaces.

For a faded rehearsal, set the priority seed to 3 and predict the height before the panel redraws. The supplied first move is this: the seed changes the priorities and therefore the tree, and the first dozen seeds give heights between 4 and 6. Say what the smallest and largest heights a twelve-key treap can possibly have are, and then say why neither extreme showed up in twelve seeds.

Common mistakes

1
Expecting the insertion order to matterIt changes the rotations and nothing else. A reader who has just come from Binary Search Trees, where the order decided everything, will look for its effect on the shape and find none — which is the result, not a failure of the experiment. The knob that changes the shape is the priority seed.
2
Reading 2 ln n as the tree's depthAt twelve keys it reads 4.970 and the counted mean depth is 2.500. It is an asymptote for the expected mean depth of a randomly built tree, with constants suppressed, and this library states it rather than proving it. Quoting it as a prediction about a small tree is quoting a growth rate as a value.
3
Expecting a height boundThere is none. A treap can be a path, with probability 1/n! for a given path shape, and nothing in the structure prevents it. If a bound that holds always is required, AVL Insertion is the structure that provides one and it pays for it with stored heights and a case analysis.

Check your understanding

✓
Finish when you can build the treap from a priority list without being told the insertion order.

You should be able to state both invariants, prove uniqueness by induction on the smallest priority, describe insertion as a leaf placement plus upward rotations, and say which of the panel's depth figures is counted, which is exact and which is an asymptote.

Note: A treap keeps the coins in the priorities and the structure in the tree. “Skip Lists” keeps the coins in the structure itself: each element chooses how many express lanes it appears in by flipping until it stops, nothing is ever rebalanced or rebuilt, and the search cost is counted by walking rather than derived from a height.

Kept in this browser only, for you. Nothing is sent anywhere and nothing checks it. Carry it to another device.

Feedback and recommendations

Something to change about this lesson? Write it down, tick it off when it is handled, and export the list when you want to act on it. Kept in this browser only: nothing is sent anywhere, and nobody is notified.

No recommendations yet for this lesson.