What are the steps of removeMin() on a heap, and why is the root replaced by the last node's key?
(1) Take the key out of the root, the minimum; (2) put the last node's key into the root; (3) delete the last node; (4) restore the heap-order property with downheap. The last node is used because it is the only node that can be removed without breaking the complete shape.
- Remove the root's key. It is the minimum and is the return value.
- Copy the last node w's key into the root. The root must not stay empty.
- Delete the last node w. The node just before it in level order becomes the new last node.
- Restore heap order with downheap, since the key now at the root is usually too large for that position.
Why not simply delete the root node? Then the tree would fall apart into two separate subtrees. And why the last node rather than, say, the smaller child of the root? Pulling up a child would leave a hole further down, which would have to be filled again, and the tree would no longer be complete. The last node is the one position whose removal keeps the shape intact, so the algorithm takes its key, fixes the shape first, and repairs the order afterwards.
The moved key is typically large for the root: w is a leaf, so its key is at least as large as every key on its path up from the bottom. That is why the order is broken and downheap has to push it back down.
Example: heap 2 → (5, 6), 5 → (9, 7), last node 7. Remove 2, move 7 to the root, delete the old node of 7: 7 → (5, 6), 5 → (9). Now downheap.
Go deeper:
VisuAlgo: Binary Heap — step-by-step animations of insert and extract-max, with the array view and pseudocode.