Traversing a binary-tree (heap) data structure (Iteration over pointers to nodes)

82 Views Asked by At

I am currently working with heaps and figuring out the details of how they work in a more implementation specific way - still, fairly theoretical/conceptual, without going into the intricacies of (pseudo-)code.

In general I am dealing with two cases: implementing a heap with an array, and implementing it with nodes as data structures, each having two nodes (pointers) as children.

Dealing with the array case is fairly easy, since I can access any element directly (random-access), so I only need to know the arithmetic relations between parent and children (i.e. if the array starts with index $n=1$, then $n_\text{left} = 2n_\text{parent}$ and $n_\text{right} = 2n_\text{parent}+1$). The array corresponds to a level-order traversing of the heap: e.g.

the array $a_n=(a,b,c,d,e,f,g)$ corresponds to the following heap

      a
     / \
    /   \
   /     \
  b       c   
 / \     / \
d   e   f   g 

Operations like restoring the heap condition down from a root node is mostly an arithmetic problem, and heapifying an arbitrary binary tree to a heap, is accomplished by traversing the array backwards restoring the heap condition down at every node I pass by.

Problem:

However, I don't seem to come up with a straight forward way of traversing the heap created with node data structures with children and parent pointers, especially because I need to do this level-order traversing without being able to jump to any node I want.

Am I in the correct direction of using a queue and putting the pointers of the nodes in the queue, and traversing it then using Breath-First-Search (BFS)? I guess the right question is how to create a binary-tree iterator?

Thank you!