Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.
We have discussed naive approach and two stack based approach in Level Order with recursion and multiple stacks
The idea behind this approach is first we have to take a queue, a direction flag and a separation flag which is NULL
- Insert the root element into the queue and again insert NULL into the queue.
- For every element in the queue insert its child nodes.
- If a NULL is encountered then check the direction to traverse the particular level is left to right or right to left. If it’s an even level then traverse from left to right otherwise traverse the tree in right to level order i.e., from the front to the previous front i.e., from the current NULL to to the last NULL that has been visited. This continues till the last level then there the loop breaks and we print what is left (that has not printed) by checking the direction to print.
Following is the implementation of the explanation
1 2 3 4 5 6 7
Time Complexity: O(n)
Auxiliary Space : O(2*n) = O(n)
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.
- Zig-Zag traversal of a Binary Tree using Recursion
- Vertical Zig-Zag traversal of a Tree
- Arrange numbers 1 to N^2 in a Zig-Zag Matrix in ascending order
- Level order traversal of Binary Tree using Morris Traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Flatten Binary Tree in order of Level Order Traversal
- Insertion in n-ary tree in given order and Level order traversal
- Rearrange a Linked List in Zig-Zag fashion | Set-2
- Connect Nodes at same Level (Level Order Traversal)
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- 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
- Check if the given array can represent Level Order Traversal of Binary Search Tree
- Level Order Tree Traversal
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Build Binary Tree from BST such that it's level order traversal prints sorted data
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.