How to iterate through a tree in a spiral?

           1 
      2              3
  4       5        6       7
8  9   10   11   12 13   14  15   

      

output in spiral order should be 1 3 2 4 5 6 7 15 14 13 12 11 10 9 8

+2


a source to share


2 answers


Think about how you will go through the root node and first level.



Can you write a function for this behavior and call it recursively?

+2


a source


This is really a variation of Breadth First Search. Breadth First Search uses a queue to get a list of nodes on the next level down. The queue is FIFO (first first). If you change the order at each level, you get this effect, so you need LIFO (the last one in the first), otherwise known as a stack.



+1


a source







All Articles