Skew heap

From Wikipedia, the free encyclopedia

A skew heap is a variant of a binary heap. In contrast to e.g. leftist heaps, there is no structural constraint on skew heaps.

There are only two constraints left:

  • The general heap order must be enforced
  • Every operation (add, remove_min, merge) of two skew heaps must be done using a special skew heap merge.

[edit] Definition

The following definition is Recursive definition.

  • A heap with only one element is a skew heap.
  • Given two skew heaps sh1 and sh2. The result of skew merging them is again a skew heap.

[edit] Skew Merge Operation

Consider two skew heaps. We want to merge them together.

  • For this we take the rightest path (i.e. the path you go along when you always go right) from the rootnode. We chop down all the nodes we encounter: for each node on the rightest path, remove its right child. Do this for both skew heaps.
  • Now we have some root nodes, which only have children on their left (if they have children at all). Now take all those root nodes you just created and sort them ascending.
  • Finally, we connect these subtrees back together. Start at the far right (the highest root node key). The parent of this root node should be the second-to-last root node (as you sorted them earlier, they indeed have an order!). Continue to do this for all the rootnodes until you have one skew heap left.
  • Now comes the trick of skewing. Every time you do connect a root node to its new parent p, flip both children of p.

This might sound strange in the beginning, because without any structural constraints, how can this structure be efficient at all? Amortised complexity analysis shows out that all operations (thus the merge operation) can be done within O(log n).

[edit] Example

An example to demonstrate the merge operation on skew heaps:

  • Chop down the nodes on the rightest path.

Image:skew1.gif

  • Sort them ascendingly.

Image:skew2.gif

  • Put 5 and 6 together.

Image:skew3.gif

  • Put 4 and previous result together.
  • Put 3 and previous result together.
  • Put 2 and previous result together.

Image:skew6.gif

  • Put 1 and previous result together. Finished.

Image:skew7.gif