Binary Tree Zigzag Level Order Traversal
Master this topic with zero to advance depth.
Binary Tree Zigzag Level Order Traversal
Zigzag BFS.
Level I: BFS + Reverse
Intuition
Process the tree level by level using a queue (standard BFS). After gathering all nodes for a specific level, check if the level index is odd. If it is, reverse the list of values before adding it to the final result.
Thought Process
- Standard BFS.
- Maintain
levelIndexstarting at 0. - Collect level nodes.
- If
levelIndex % 2 != 0, reverse level list. - Increment
levelIndex.
Detailed Dry Run
| Level | Nodes | Reverse? | State |
|---|---|---|---|
| 0 | [3] | No | [[3]] |
| 1 | [9, 20] | Yes | [[3], [20, 9]] |
| 2 | [15, 7] | No | [[3], [20, 9], [15, 7]] |
Level II: Two Stacks
Intuition
Instead of reversing level results after-the-fact, we can use two stacks to maintain the order. One stack processes Left-to-Right, and the other Right-to-Left. As we pop from one stack, we push its children into the other stack in an order that keeps the next level correctly oriented.
Logic
- Stack1 (L to R): Push Left child, then Right child to Stack2.
- Stack2 (R to L): Push Right child, then Left child to Stack1.
Detailed Dry Run
S1: [3]. Pop 3, S2: [9, 20]. Pop 20, S1: [7, 15]. Pop 9... result levels built directly in order.
Level III: Optimal (BFS + Double-Ended Queue)
Intuition
Thought Process
Directly inserting at either the head or tail of a Deque based on the current level's direction avoids the need for an explicit Reverse step. This is more efficient as we determine the correct spot for each node exactly once.
Logic
- Use a standard BFS queue.
- For each level, initialize an empty Deque.
- If
LevelIndexis even: Add to the back (tail). - If
LevelIndexis odd: Add to the front (head).
Complexity
- Time:
- Space: (Queue size)
Detailed Dry Run
| Level | Node | Direction | Deque State |
|---|---|---|---|
| 1 | 9 | Left to Right | [9] |
| 1 | 20 | Left to Right | [9, 20] |
| 2 | 15 | Right to Left | [15] |
| 2 | 7 | Right to Left | [7, 15] |
⚠️ Common Pitfalls & Tips
While unshift in JS or appendleft in Python is for Deques, using them on standard arrays can be per operation. Be sure to use appropriate data structures.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.