Binary Tree Zigzag Level Order Traversal
Given the root of a binary tree, return the values of its nodes level by level in zigzag order: the first level left to right, the next level right to left, and so on, alternating each level.
Trees in the examples and tests are written in level order, with null for a missing child.
Example 1
Input: root = [3, 9, 20, null, null, 15, 7] Output: [[3], [20, 9], [15, 7]] 3 / \ 9 20 / \ 15 7
Example 2
Input: root = [1] Output: [[1]]
Constraints
- The tree has between
0and2000nodes. -100 <= Node.val <= 100
Approach
A breadth-first search with a queue already visits the tree level by level. Noting the queue's size at the start of each level tells you exactly how many nodes belong to it, so you can collect one level at a time.
Zigzag order only changes the direction each level is reported in, not which nodes are on it. Keep a flag that starts as left to right and flips after every level. Collect each level left to right as usual, and reverse it before adding it to the result when the flag says right to left. Reversing a level costs time proportional to its size, so the whole traversal stays linear.
Steps
- If the tree is empty, return an empty list.
- Put the root in a queue and set
left_to_rightto true. - While the queue isn't empty, note its size and remove that many nodes, recording their values and adding their children to the queue.
- Reverse the level if
left_to_rightis false, add it to the result and flip the flag. Return the result when the queue is empty.
from collections import deque
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def zigzag_level_order(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)): # exactly the nodes on this level
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level if left_to_right else level[::-1])
left_to_right = not left_to_right
return levelsComplexity
- Time:
O(n). Each node is added to the queue and removed once, and each value is reversed at most once. - Space:
O(n). The queue holds up to one full level.
Common mistakes
- Swapping the order you add children to the queue instead of reversing the level. That changes which order the next level's nodes come out in and scrambles deeper levels.
- Flipping the direction for every node instead of once per level.
- Returning
[[]]for an empty tree instead of[].