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 | Using one stack and one queue
- Level order traversal in spiral form using stack and multimap
- Level order traversal in spiral form
- Reverse Level Order traversal in spiral form
- 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
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- deque::at() and deque::swap() in C++ STL
- deque::front() and deque::back() in C++ STL
- deque::clear() and deque::erase() in C++ STL
- deque::operator= and deque::operator in C++ STL
- Check if two trees are mirror of each other using level order traversal
- Zig Zag Level order traversal of a tree using single array
- Density of Binary Tree using Level Order Traversal
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Level order traversal line by line | Set 3 (Using One Queue)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.