Binary Tree Zigzag Level Order Traversal
Level-order traversal where each level alternates direction — left→right, then right→left, then left→right…
Key concepts at a glance — for those who already know the basics.
Problem Statement
Binary Tree Zigzag Level Order Traversal
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [20, 9], [15, 7]]
Constraints
- The number of nodes in the tree is in range [0, 2000].
- Node values are in range [-100, 100].
01 · The rule
BFS level-by-level, but flip the collection direction each level
Use a standard BFS queue. After collecting each level's nodes, check a boolean flag: if left_to_right is True, keep the level as-is; otherwise reverse it before appending to results. Toggle the flag after every level.
02 · How to think
len(queue) at the start of each iteration to know exactly how many nodes belong to the current level.left_to_right after every level.03 · Code (Python)
from collections import deque
def zigzagLevelOrder(root):
if not root: return []
result = []
queue = deque([root]) # standard BFS queue
left_to_right = True # direction flag
while queue:
level_size = len(queue) # freeze current level count
level = []
for _ in range(level_size):
node = queue.popleft()
level.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
if not left_to_right: # flip if right-to-left level
level.reverse()
result.append(level)
left_to_right = not left_to_right # toggle for next level
return result04 · Example tree & zigzag output
05 · Complexity
Ready to see it in action?
Step through the visualizer to watch the algorithm state update live.