Binary Tree Zigzag Level Order Traversal
List a tree level by level, alternating left-to-right and right-to-left, with a normal BFS and a flag.
The problem
You get the root of a binary tree. Return its values level by level, but switch direction on every level: the first level from left to right, the second from right to left, the third from left to right again, and so on.
Input root = [6, 4, 9, 2, 5, 7, 11, 1, null, null, 3]
Output [[6], [9, 4], [2, 5, 7, 11], [3, 1]]
The second and fourth levels are read from right to left: 9 before 4, and 3 before 1.
Key constraint: Only the reading direction changes from level to level; which nodes belong to a level stays the same.
How to spot the pattern
- The output is grouped by level, like a level order traversal.
- Every second level has to come out in reverse order.
The idea
Which nodes are on a level doesn't depend on the direction, so run the usual level-by-level BFS and always push children left before right. Only the way you write each level changes: collect its values from left to right and reverse the list on every second level. Reversing a level costs as much as reading it, so the total work stays O(n).
Brute force: For each depth, walk the whole tree to collect that level and reverse every second one, which takes O(n * h) time.
Step by step
- 1If the root is null, return an empty list; otherwise put the root in a queue and set
leftToRightto true. - 2For each level, pop
sizenodes, collect their values in order and push their children, left before right. - 3If
leftToRightis false, reverse the level's values. - 4Add the level to the answer, flip
leftToRight, and return the answer when the queue is empty.
See the pattern move
The tree bfs pattern on a small example. Step through it, or press play.
Code
from collections import deque
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []
levels = []
queue = deque([root])
left_to_right = True
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
# Children always go in left before right; only the output order changes.
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if not left_to_right:
level.reverse()
levels.append(level)
left_to_right = not left_to_right
return levelsComplexity
Time
O(n)
Space
O(n)
Each node is pushed, popped and written once, and reversing a level touches each of its values once more; the answer stores all n values.
Watch out for
- Changing the order in which children are pushed instead of the order values are written, which scrambles the levels further down.
- Flipping the direction after every node instead of after every level.
Follow-up questions
Can you avoid the reverse step?
Yes: give the level's list size slots and write the i-th popped value at index i or size - 1 - i, depending on the direction. A deque that adds values at the front on right-to-left levels works too.
Can you do it with two stacks?
Yes: pop nodes from one stack and push their children onto the other, left child first on left-to-right levels and right child first on the others. The stacks reverse the order for you.
In Hinglish
Normal level order hi karo, bas har doosre level ki list ulti kar do. Bacchon ko queue mein hamesha left se right hi daalna.