I am looking for a way to implement an iterator on binary heaps (maximum or minimum).
That is, by using it’s nextNode() function for the i-th time, can get the i-th (greater or smaller) element in the heap.
Note that this operation happens without actually extracting the heap’s root!
My initial thoughts were:
- Actually extract i elements, push them into a stack, and then insert them back into the heap after getting the i-th value. This takes O(i*log(n)) for each function call.
- Keep an auxiliary sorted data structure, which can allow to lookup the next value in O(1), however updates would take O(n).
I understand these approaches eliminate the benefits of using heaps, so I’m looking for a better approach.