The Height of a Heap

peek reads the root, so it is . add swims a value up and remove sinks a value down, one swap per level, so each does at most swaps, where is the height of the tree. Each also has to find one node first: add needs the next open slot, and remove needs the last node. How that is done depends on how the tree is stored. The next chapter stores the tree in two ways, and both find these nodes in or less. So add and remove are , and their cost depends on the height of the tree.

The height of a complete tree

We need the height in terms of the number of elements .

In the search tree chapter we worked this out for a perfect binary tree, where every level is full. Its levels hold nodes, which add up to , so its height is about .

A complete tree of height has every level full except possibly the last. The full part is levels through , which is a perfect tree of height holding nodes. The last level, level , holds at least node and at most a full nodes. If it held no nodes, the tree would be shorter than . Add the last level to the full part, and the total falls between

From , taking of both sides gives . From , taking gives , that is, . So the height is between and , which means it is about .

A quick check on the six-node heap we have been drawing, which has height :

               ╭───╮
               │ 1 │
               ╰─┬─╯
       ┌─────────┴─────────┐
     ╭─┴─╮               ╭─┴─╮
     │ 3 │               │ 2 │
     ╰─┬─╯               ╰─┬─╯
  ┌────┴────┐          ┌───┘
╭─┴─╮     ╭─┴─╮      ╭─┴─╮
│ 5 │     │ 4 │      │ 8 │
╰───╯     ╰───╯      ╰───╯

Levels and are full, with and nodes, and level holds of its slots, for in all. The bounds say , and , which rounds down to . That is the height.