A heap is a tree in which every node's key is greater than or equal to, or less than or equal to, its parent's key.
A heap in which every node's key is greater than or equal to its parent's key is called a min-heap; otherwise it is called a max-heap. STL's priority_queue is in fact a max-heap.
The main operations supported by a (min-)heap are: inserting a number, querying the minimum, deleting the minimum, merging two heaps, and decreasing the value of an element.
Some powerful heaps (mergeable heaps) can also efficiently support operations such as \.
Even more powerful heaps also support persistence, meaning that any historical version can be queried or operated on to produce a new version.
Heap classifications
| Operation Data structure1 | Pairing heap | Binary heap | Leftist tree | Binomial heap | Fibonacci heap |
|---|---|---|---|---|---|
| Insert (insert) | 2 | ||||
| Find minimum (find-min) | 34 | ||||
| Delete minimum (delete-min) | 4 | 4 | |||
| Merge (merge) | |||||
| Decrease an element's value (decrease-key) | (lower bound , upper bound )4 | 4 | |||
| Supports persistence |
By convention, an unqualified reference to a “heap” usually means a binary heap.
Footnotes
-
The complexity of a single insertion is , but for consecutive insertions, a binomial heap containing only the elements to be inserted can be created and then merged with the original binomial heap, giving an amortized complexity of . ↩
-
A pointer to the minimum element can be maintained, and that pointer can be updated during other operations, allowing queries in time. ↩