Given a binary tree and we have to find the spiral order traversal of the tree and return the list containing the elements. Spiral order Traversal: Starting from level 0 for root node, for all the even levels we print the node's value from right to left and for all the odd levels we print the node's value from left to right.
The idea is to first calculate the height of the tree, then recursively traverse each level and print the level order traversal according to the current level being odd or even.
Steps to solve the problem:
Find the height h of the binary tree.
Use a boolean flag variable ltr (left-to-right), start as false.
For each level ,Call printGivenLevel(root, level, ltr).
Toggle ltr after each level.
If node is null → return.
If level == 1 → process the current node.
If level > 1,If ltr → recurse left → right otherwise → recurse right → left.
Output
1 2 3 4 5 6 7
Using Two Stacks - O(n) Time and O(n) Space
The idea is to use two stacks. One stack s1 is used to traverse the current level and the other stack s2 is used to store the nodes of next level.
Steps to solve the problem:
Initialize two stacks s1 and s2, push root into s1.
While either stack is not empty:
From s1: pop nodes, add to result, push right → left children into s2.
From s2: pop nodes, add to result, push left → right children into s1.