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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Level Order Tree Traversal
- Reverse Level Order Traversal
- Construct BST from its given level order traversal
- Boundary Level order traversal of a Binary Tree
- Zig Zag Level order traversal of a tree using single array
- Density of Binary Tree using 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
- 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.