Given the root of a binary tree, perform a zigzag (spiral) level order traversal. For odd-numbered levels, traverse the nodes from left to right and for even-numbered levels, traverse the nodes from right to left.
The idea is to first calculate the height of the tree, and then recursively traverse each level to perform a level order traversal according to the current levelβs direction.
The traversal alternates directions at each level to achieve a zigzag pattern:
At the first level, nodes are visited from left to right.
At the next level, nodes are visited from right to left.
This pattern continues for all levels by flipping the direction after each level.
Output
20 22 8 4 12 11 14 10
Time Complexity: O(n*h), where n is the number of nodes and h is the height of the tree. For each height from 1 to n, we are recursively traversing the tree from root in order to get nodes at a certain height. Auxiliary Space: O(h)
[Expected Approach - 1] - Using Two Stacks - O(n) Time and O(n) Space
The idea is to perform a zigzag (spiral) level order traversal of a binary tree using two stacks instead of recursion.
s1 stores nodes of the current level, and s2 stores nodes of the next level.
Nodes in s1 are processed from top to bottom, and their children are pushed onto s2 in left β right order.
Nodes in s2 are then processed from top to bottom, and their children are pushed onto s1 in right β left order.
By alternating the order of pushing children between the two stacks at each level, the traversal naturally alternates direction, achieving the zigzag pattern.
Output
20 22 8 4 12 11 14 10
[Expected Approach - 2] - Using Deque - O(n) Time and O(n) Space
The idea is to use a deque to store nodes level by level and alternate the direction of traversal at each level.
For a level traversed left to right, nodes are popped from the front, and their children are added to the back in left β right order.
For a level traversed right to left, nodes are popped from the back, and their children are added to the front in right β left order.