Zig Zag Level order traversal of a tree using single array
Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.
We have discussed naive approach and two stack based approach in Level Order with recursion and multiple stacks
The idea behind this approach is first we have to take a queue, a direction flag and a separation flag which is NULL
- Insert the root element into the queue and again insert NULL into the queue.
- For every element in the queue insert its child nodes.
- If a NULL is encountered then check the direction to traverse the particular level is left to right or right to left. If it’s an even level then traverse from left to right otherwise traverse the tree in right to level order i.e., from the front to the previous front i.e., from the current NULL to to the last NULL that has been visited. This continues till the last level then there the loop breaks and we print what is left (that has not printed) by checking the direction to print.
Following is the implementation of the explanation
1 2 3 4 5 6 7
Time Complexity: O(n)
Auxiliary Space : O(2*n) = O(n)