Professional Documents
Culture Documents
RandomizedBST Treap
RandomizedBST Treap
Lecture #23
Data Structures
Henry Kautz
Winter Quarter 2002
1
Randomized Data Structures
• We’ve seen many data structures with good
average case performance on random inputs, but
bad behavior on particular inputs
– Binary Search Trees
• Instead of randomizing the input (since we
cannot!), consider randomizing the data structure
– No bad inputs, just unlucky random numbers
– Expected case good behavior on any input
2
What’s the Difference?
• Deterministic with good average time
– If your application happens to always use the “bad” case,
you are in big trouble!
• Kind of like an
insurance policy
for your algorithm!
3
Treap Dictionary Data Structure
heap in yellow; search tree in blue
• Treaps have the binary
search tree 2
– binary tree property 9
– search tree property
6 4
• Treaps also have the 7 18
heap-order property!
– randomly assigned 7 9 10
priorities 8 15 30
Legend:
priority 15
key 12 4
Treap Insert
• Choose a random priority
• Insert as in normal BST
• Rotate up until heap order is restored (maintaining
BST property while rotating)
insert(15)
2 2 2
9 9 9
6 14 6 14 6 9
7 12 7 12 7 15
7 7 9 7 145
8 8 15 8 12
Tree + Heap… Why Bother?
Insert data in sorted order into a treap; what shape
tree comes out?
7 6 6 15
8 7 7 12
Legend:
priority 7 7
key 8 8 6
Treap Delete
• Find the key delete(9)
2 6
rotate left 7 rotate left
• Increase its value to 9
• Rotate it to the fringe 6 9
7 15
• Snip it off 9
7 15 7
6 8 12 9
7 rotate right 8 15
7 15
8 12
9
9
15 15
7
12
Treap Delete, cont.
6 6
6 rotate right
rotate right 7 7
7
7 7 7
8 8 8
9 9
9 15 15
9 15
15 15 9 12
12 15
12 9
snip!
8
Treap Summary
• Implements Dictionary ADT
– insert in expected O(log n) time
– delete in expected O(log n) time
– find in expected O(log n) time
– but worst case O(n)
• Memory use
– O(1) per node
– about the cost of AVL trees
• Very simple to implement, little overhead – less
than AVL trees
9