10. ZigZag Tree Traversal
β GFG solution to the ZigZag Tree Traversal problem: perform level order traversal in alternating left-to-right and right-to-left directions using efficient queue-based techniques. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given the root of a binary tree, you need to perform a zigzag level order traversal. In this traversal:
Odd-numbered levels (1st, 3rd, 5th, etc.) are traversed from left to right.
Even-numbered levels (2nd, 4th, 6th, etc.) are traversed from right to left.
Return the nodes in the order they appear during this zigzag traversal.
π Examples
Example 1
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: [1, 3, 2, 4, 5, 6, 7]
Explanation:
Level 1 (left to right): [1]
Level 2 (right to left): [3, 2]
Level 3 (left to right): [4, 5, 6, 7]
Final result: [1, 3, 2, 4, 5, 6, 7]Example 2
π Constraints
$1 \le \text{number of nodes} \le 10^5$
$1 \le \text{node->data} \le 10^5$
β
My Approach
The optimal approach uses Queue-Based Level Order Traversal with Index Manipulation to achieve zigzag ordering efficiently:
Queue with Index Positioning
Initialize Data Structures:
Use a queue for standard level-order traversal (BFS).
Maintain a boolean flag
ltr(left-to-right) to track current direction.Create result vector to store final traversal order.
Process Each Level:
For each level, determine its size to process all nodes at current depth.
Create a temporary level vector of the exact size needed.
Smart Index Placement:
For left-to-right levels: place nodes at their natural index position (0, 1, 2, ...).
For right-to-left levels: place nodes at reversed index positions (size-1, size-2, ...).
This eliminates the need for explicit reversal operations.
Add Children to Queue:
Always add left child first, then right child (standard BFS order).
The queue maintains proper level-by-level traversal regardless of zigzag pattern.
Toggle Direction:
After processing each level, flip the
ltrflag.Append the level vector to result and continue to next level.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the number of nodes in the binary tree. Each node is visited exactly once during the level order traversal, and inserting nodes at calculated indices takes constant time.
Expected Auxiliary Space Complexity: O(w), where w is the maximum width of the tree. The queue stores at most one complete level of nodes at any given time, which in the worst case (complete binary tree) is approximately n/2 nodes at the last level.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Deque-Based Approach
π‘ Algorithm Steps:
Use a deque to enable bidirectional insertion and removal.
Track direction flag to determine front or back processing.
For left-to-right levels, process from front and add children normally.
For right-to-left levels, process from back and reverse child insertion order.
π Complexity Analysis:
Time: β±οΈ O(n) - Visit each node exactly once
Auxiliary Space: πΎ O(w) - Width of tree for deque storage
β
Why This Approach?
Natural bidirectional processing with deque
Direct zigzag traversal without reversing
Efficient for wide trees with controlled memory
π 3οΈβ£ Two-Stack Approach
π‘ Algorithm Steps:
Maintain two stacks for alternating level processing.
Stack s1 processes left-to-right by pushing left child first.
Stack s2 processes right-to-left by pushing right child first.
Alternate between stacks for automatic zigzag pattern.
π Complexity Analysis:
Time: β±οΈ O(n) - Linear traversal of all nodes
Auxiliary Space: πΎ O(w) - Maximum width of tree across both stacks
β
Why This Approach?
Classic stack-based zigzag implementation
Natural LIFO ordering produces zigzag automatically
Minimal overhead with simple push-pop operations
π 4οΈβ£ Recursive Level Order with Reversal
π‘ Algorithm Steps:
Use level-order traversal with level tracking.
Store nodes at each level in separate vectors.
Reverse alternate level vectors based on level number.
Concatenate all levels to produce final zigzag order.
π Complexity Analysis:
Time: β±οΈ O(n) - Each node visited once plus reversals
Auxiliary Space: πΎ O(w) - Level storage and queue combined
β
Why This Approach?
Straightforward standard BFS with modification
Easy to understand and debug
Flexible for adding additional level processing
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π’ Queue with Index
π’ O(n)
π’ O(w)
π Clean and efficient
πΎ Extra vector per level
π Deque-Based
π’ O(n)
π’ O(w)
β‘ True bidirectional access
π§ Slightly complex logic
π Two-Stack
π’ O(n)
π’ O(w)
π― Classic pattern
π Two data structures needed
π BFS with Reversal
π’ O(n)
π’ O(w)
π Simple BFS modification
π Extra reversal operations
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Clean readable code
π₯ Queue with Index
β β β β β
π Memory optimization
π₯ Deque-Based
β β β β β
π§ Classic pattern learning
π₯ Two-Stack
β β β β β
π― Simplicity priority
π BFS with Reversal
β β β β β
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated