![]() | ||
A skew heap (or self-adjusting heap) is a heap data structure implemented as a binary tree. Skew heaps are advantageous because of their ability to merge more quickly than binary heaps. In contrast with binary heaps, there are no structural constraints, so there is no guarantee that the height of the tree is logarithmic. Only two conditions must be satisfied:
Contents
- Definition
- Merging two heaps
- Non recursive merging
- Adding values
- Removing values
- Implementation
- References
A skew heap is a self-adjusting form of a leftist heap which attempts to maintain balance by unconditionally swapping all nodes in the merge path when merging two heaps. (The merge operation is also used when adding and removing values.)
With no structural constraints, it may seem that a skew heap would be horribly inefficient. However, amortized complexity analysis can be used to demonstrate that all operations on a skew heap can be done in O(log n).
Definition
Skew heaps may be described with the following recursive definition:
Merging two heaps
When two skew heaps are to be merged, we can use a similar process as the merge of two leftist heaps:
Before:
after
Non-recursive merging
Alternatively, there is a non-recursive approach which is more wordy, and does require some sorting at the outset.
Adding values
Adding a value to a skew heap is like merging a tree with one node together with the original tree.
Removing values
Removing the first value in a heap can be accomplished by removing the root and merging its child subtrees.
Implementation
In many functional languages, skew heaps become extremely simple to implement. Here is a complete sample implementation in Haskell.