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
- 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
- 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
- Construct BST from its given level order traversal | Set-2
- Level Order Tree Traversal
- Reverse Level Order Traversal
- Density of Binary Tree using Level Order Traversal
- Check if two trees are mirror of each other using level order traversal
- Zig Zag Level order traversal of a tree using single queue
- Level order traversal with direction change after every two levels
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.