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
- 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)
- Level Order Tree Traversal
- Construct BST from its given level order traversal
- Reverse Level Order Traversal
- Level order traversal with direction change after every two levels
- Check if two trees are mirror of each other using level order traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Perfect Binary Tree Specific Level Order Traversal
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Check if the given array can represent Level Order Traversal of Binary Search Tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap