The Treap: A Hybrid BST and Heap
A Treap
-
Suppose that each BiTree contains an object that has a distinct key
and priority,
-
and that we simultaneously maintain the BST property on the key and the
heap property on the priority.
Insertion
-
The insertion procedure is straightforward:
-
Insert the node (key, priority, value) by key, just
like a BST.
-
If the node's priority is less than its parent's priority,
rotate around the parent, lifting the node above its parent.
-
For example, suppose we had inserted (key=73, priority=6) into the following
treap.
Examples of Insertion
-
What happens if we insert (key=49, priority=19) into the following treap?
The Punchline
-
Suppose that we insert (key=3,priority=56), (16,33), (22,89), (31,17),
(41,49), (53,22), and (69,36) in order of increasing key.
-
What happens? Note: ignoring the priority, this produces a worst-case
BST.
...
-
The punchline: The same treap will result regardless of the order of
insertion.
-
Suppose that you don't require the priority for your application.
The priority can be:
-
A randomly generated number
-
A ``hash'' of the key