Presentation is loading. Please wait.

Presentation is loading. Please wait.

Treaps.

Similar presentations


Presentation on theme: "Treaps."— Presentation transcript:

1 Treaps

2 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.

3 Keys a b c d e f g Priorities d 1 a3 f 2 c 4 e 5 g 6 b 7

4 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!

5 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.

6 Rotation Review – R to Root
x r B C C r x B A

7 Rotation Review – R to Root
x r B C C r x B A

8 Deletion Given an existing treap, how do we delete a node?
Rotate it down to a leaf, and then delete it.

9 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)

10 Oh god, a proof Suppose we search for a node m.

11 Oh god, a proof Xi = 1 if i is an ancestor of m 0 otherwise

12 Oh god, a proof depth(m) = Σ1 ≤ i ≤ nXi

13 E[depth(m)] = E[Σ1 ≤ i ≤ nXi]
Oh god, a proof E[depth(m)] = E[Σ1 ≤ i ≤ nXi]

14 E[depth(m)] = Σ1 ≤ i ≤ nE[Xi]
Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ nE[Xi]

15 Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ nPr[ i is an ancestor of m ]

16 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

17 Finding Pr[ i is an ancestor of m ]
Suppose i > m. By symmetry:

18 Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ nPr[ i is an ancestor of m ]

19 Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ m Σm+1 ≤ i ≤ n

20 Oh god, a proof E[depth(m)] = Σ1 ≤ i ≤ m Σm+1 ≤ i ≤ n ≤ 2 log n

21 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)

22 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

23 COUNTING ROTATIONS Let Di be the event that i is in the left subtree (red) m CLAIM:

24 Informal proof or Game of Darts
1 i m n Don’t care Don’t care Remaining darts Second dart First dart

25 COUNTING ROTATIONS Let D*i be the event that i is in the right subtree (blue) m CLAIM:

26 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)


Download ppt "Treaps."

Similar presentations


Ads by Google