Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.
You are allowed to use only one stack.
We have seen recursive and iterative solutions using two stacks . In this post, a solution with one stack and one queue is discussed. The idea is to keep on entering nodes like normal level order traversal, but during printing, in alternative turns push them onto the stack and print them, and in other traversals, just print them the way they are present in the queue.
Following is the CPP implementation of the idea.
1 2 3 4 5 6 7
Time Complexity : O(n)
Auxiliary Space : O(n)
- Level order traversal in spiral form
- Reverse Level Order traversal in spiral form
- Zig Zag Level order traversal of a tree using single queue
- Level order traversal line by line | Set 3 (Using One Queue)
- Connect Nodes at same Level (Level Order Traversal)
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Construct BST from its given level order traversal | Set-2
- Level Order Tree Traversal
- Reverse Level Order Traversal
- Construct BST from its given level order traversal
- Check if two trees are mirror of each other using level order traversal
- Level order traversal with direction change after every two levels
- Density of Binary Tree using Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Perfect Binary Tree Specific Level Order Traversal
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.