![]() |
VOOZH | about |
Given a binary tree, the task is to print the reverse level order in spiral form.
Examples:
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(n2) [O((n)+(n-1)+(n-2)+...] in case of a skewed tree taken as input.
Auxiliary Space: O(n) for call stack since using recursion.
Iterative Implementation -
The above problem can be solved with the help of queue and stack. Just perform a normal spiral traversal, use stack to use reverse the elements alternatively. Below is the implementation of the same -
8 7 4 6 9 3 5
Time Complexity: O(N)
Auxiliary Space: O(N)
Improved by :HarendraSingh22