Given a Binary Tree, the task is to print spiral order traversal of the given tree. For below tree, the function should print 1, 2, 3, 4, 5, 6, 7.
Input: 1 / \ 3 2 Output : 1 3 2 Input : 10 / \ 20 30 / \ 40 60 Output : 10 20 30 60 40
We have seen recursive and iterative solutions using two stacks and an approach using one stack and one queue. In this post, a solution with one deque is discussed. The idea is to use a direction variable and decide whether to pop elements from the front or from the rear based on the value of this direction variable.
Below is the implementation of the above approach:
10 20 30 60 40
Time Complexity: O(N)
Space Complexity: O(N)
where N is the number of Nodes
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Level order traversal in spiral form
- Reverse Level Order traversal in spiral form
- Level order traversal in spiral form | Using one stack and one queue
- Level order traversal in spiral form using stack and multimap
- Level order traversal of Binary Tree using Morris Traversal
- Connect Nodes at same Level (Level Order Traversal)
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Insertion in n-ary tree in given order and Level order traversal
- Construct BST from its given level order traversal | Set-2
- Construct BST from its given level order traversal
- Reverse Level Order Traversal
- Level Order Tree Traversal
- Boundary Level order traversal of a Binary Tree
- Specific Level Order Traversal of Binary Tree
- Level order traversal with direction change after every two levels
- Density of Binary Tree using Level Order Traversal
- Zig Zag Level order traversal of a tree using single array
- Check if two trees are mirror of each other using level order traversal
- 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.