Given a binary tree, the task is to print the reverse level order in spiral form.
Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4 5 6 7 3 2 1 Input: 5 / \ 6 4 / \ / 7 1 8 \ \ 3 10 Output: 3 10 8 1 7 6 4 5
Approach: The idea is to traverse the tree in a Reverse Level Order manner but with a slight modification. We will use a variable flag and initially set it’s value to one. As we complete the reverse level order traversal of the tree, from left to right we will set the value of flag to zero, so that next time we traverse the Tree from right to left and as we complete the traversal we set it’s value back to one. We will repeat this whole step until we have traversed the Binary Tree completely.
Below is the implementation of the above approach:
8 7 4 6 9 3 5
Time Complexity Analysis : The best case time complexity of reverseSpiral() is O(n+n/2+n/4…) = O(n) in case of a perfect binary tree. And the worst case time complexity is O(n**2) [O((n)+(n-1)+(n-2)+…] in case of a skewed tree taken as input.
Improved by :HarendraSingh22
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Level order traversal in spiral form
- Level order traversal in spiral form | Using Deque
- Level order traversal in spiral form | Using one stack and one queue
- Reverse Level Order Traversal
- Reverse Clockwise spiral traversal of a binary tree
- Connect Nodes at same Level (Level Order Traversal)
- Reverse Anti Clockwise Spiral Traversal of a Binary Tree
- 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
- Construct BST from its given 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 array
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.