Treaps
Definition A treap is a binary search tree in which each node has both a key and a priority. Nodes are ordered in an in-order fashion by their keys and are heap-ordered by their priorities.
Keys a b c d e f g Priorities 3 7 4 1 5 2 6 d 1 a3 f 2 c 4 e 5 g 6 b 7
Existence Why must a treap with any priorities exist? We can always create one by sorting by priority and then inserting as a binary search tree!
Insertion How do we insert into an existing treap? Insert as a BST, then perform a series of tree rotations to enforce the heap ordering invariant.
Rotation Review – R to Root x r B C C r x B A
Rotation Review – R to Root x r B C C r x B A
Deletion Given an existing treap, how do we delete a node? Rotate it down to a leaf, and then delete it.
Theorem Expected # of comparisons for insert, search, delete is Θ(log n) Equivalent to showing the expected height is Θ(log n) We will prove a weaker statement: Expected height of a single node is O(log n)
Oh god, a proof Suppose we search for a node m.
Oh god, a proof Xi = 1 if i is an ancestor of m 0 otherwise
Oh god, a proof depth(m) = Σ1 ≤ i ≤ nXi
E[depth(m)] = E[Σ1 ≤ i ≤ nXi] Oh god, a proof E[depth(m)] = E[Σ1 ≤ i ≤ nXi]
E[depth(m)] = Σ1 ≤ i ≤ nE[Xi] Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ nE[Xi]
Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ nPr[ i is an ancestor of m ]
Finding Pr[ i is an ancestor of m ] Suppose i ≤ m. Consider [i, i+1, …, m-1, m] i must have the highest priority out of these
Finding Pr[ i is an ancestor of m ] Suppose i > m. By symmetry:
Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ nPr[ i is an ancestor of m ]
Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ m + Σm+1 ≤ i ≤ n
Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ m + Σm+1 ≤ i ≤ n ≤ 2 log n
COUNTING ROTATIONS Theorem. The expected number of rotations for insertion or deletion is < 2 Right-most nodes in the left subtree – L(x) Left-most nodes in the right subtree – R(x) x R(x) L(x)
COUNTING ROTATIONS Lemma. Consider the treap obtained right after insertion of node x. Then the number of rotations performed during insertion of x is L(x)+R(x) x x
COUNTING ROTATIONS Let Di be the event that i is in the left subtree (red) m CLAIM:
Informal proof or Game of Darts 1 i m n Don’t care Don’t care Remaining darts Second dart First dart
COUNTING ROTATIONS Let D*i be the event that i is in the right subtree (blue) m CLAIM:
COUNTING ROTATIONS Lemma. Consider the treap obtained right after insertion of node x. Then the number of rotations performed during insertion of x is L(x)+R(x)