42A. Heaps and Priority Queues

A heap is a data structure that is useful for implementing a priority queue efficiently. There are actually two versions, min-heaps and max-heaps. We will start with min-heaps.

A heap is a tree. Each node in the tree holds an item and a priority. But it is simpler to concentrate on only one of those, the priority. Imagine the item to be attached to it but not written down. For simplicity we assume that the priorities are integers. They could just as well be real numbers or even strings.

There are two requirements that a min-heap must meet.

  1. (Ordering requirement) The priority in a node must be no larger than the priority in each of that node's children (if it has any children). Duplicate priorities are allowed.

  2. (Structural requirement) The levels of a tree are defined by their distance from the root. The root is the only node in level 0. The children of the root form level 1. The nodes at distance 2 from the root form level 2, etc. The structural requirement is that each of the following is true.

    1. Every level of the tree must be completely full, having the maximum number of nodes that it can possibly have, with the possible exception of the highest numbered level, which we call the bottom level.

    2. Nodes in the bottom level must be as far to the left as possible. There must be no gaps between nodes.

For example, the following is a min-heap. (Only the priority in each node is shown.)

Notice that it obeys both the ordering and the structural requirement.