Search code examples
arraysalgorithmlanguage-agnosticheapcontainers

Traversing a complete binary min heap


I am not sure how to traverse the tree structure below so that the nodes are always in ascending order. Heapifying the array [9 8 7 6 5 4 3 2 1 0] results in the array [0 1 3 2 5 4 7 9 6 8] which I think corresponds to this representation:

heap drawing

Wanting to keep the array as is (because I want to do efficient inserts later) how can I efficiently traverse it in ascending order? (That is visiting the nodes in this order [0 1 2 3 4 5 6 7 8 9])


Solution

  • Just sort the array. It will still be a min-heap afterward, and no other algorithm is asymptotically more efficient.