LeetCode 103: Binary Tree Zigzag Level Order Traversal — Python Solution

LeetCode 103: Binary Tree Zigzag Level Order Traversal is a Medium binary tree bfs problem. This Python walkthrough develops an alternating level output solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicBinary Tree BFS
Reusable patternalternating level output
ComplexityO(n) time and O(w) space

Recognizing the pattern

Breadth-first search is the natural fit when the answer is grouped by depth or depends on the first visit at a level.

For this problem specifically, run ordinary BFS and reverse the collected values on alternating levels. The invariant worth writing beside the code is: Each level is collected left-to-right before the direction flag determines output order.

Step-by-step algorithm

  1. Identify the input state consumed by zigzagLevelOrder(root) and initialize the data required by the alternating level output pattern.
  2. Run ordinary BFS and reverse the collected values on alternating levels.
  3. After each update, verify the page’s central invariant: Each level is collected left-to-right before the direction flag determines output order.
  4. Finish only after the boundary behavior is covered: The root level is left-to-right; direction flips after every level.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

from collections import deque

class Solution:
    def zigzagLevelOrder(self, root):
        if not root:
            return []
        queue, answer, reverse = deque([root]), [], False
        while queue:
            level = []
            for _ in range(len(queue)):
                node = queue.popleft(); level.append(node.val)
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
            answer.append(level[::-1] if reverse else level)
            reverse = not reverse
        return answer

Reading the implementation

The main entry point is zigzagLevelOrder(root). The named working state includes queue, level, node, reverse; those variables make the alternating level output state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, run ordinary BFS and reverse the collected values on alternating levels.

Correctness argument

Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.

Inductive step. Run ordinary BFS and reverse the collected values on alternating levels. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so each level is collected left-to-right before the direction flag determines output order.

Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.

Complexity and trade-offs

O(n) time and O(w) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Depth-first search can carry an explicit depth and build the same result, but level boundaries are less direct. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().zigzagLevelOrder(root)==[[3],[20,9],[15,7]]

Common mistakes and edge cases

  • Problem-specific boundary: The root level is left-to-right; direction flips after every level.
  • Pattern-level pitfall: Capture the current queue length before processing a level so children do not leak into the same batch.
  • Invariant check: after every update, confirm that each level is collected left-to-right before the direction flag determines output order.

Interview review checklist

  • Explain why alternating level output matches the structure of this input.
  • State the invariant in one sentence before tracing code: Each level is collected left-to-right before the direction flag determines output order.
  • Derive O(n) time and O(w) space from how many times each element or state is visited.
  • Test the boundary explicitly: The root level is left-to-right; direction flips after every level.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 102. Binary Tree Level Order Traversal · Next: 530. Minimum Absolute Difference in BST