Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #103: Binary Tree Zigzag Level Order Traversal

In this guide, we solve Leetcode #103 Binary Tree Zigzag Level Order Traversal in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Tree, Breadth-First Search, Binary Tree

Intuition

We need level-by-level exploration or shortest steps, which is ideal for BFS.

A queue naturally models the frontier of the search.

Approach

Push initial nodes into a queue and expand in layers.

Track visited nodes to prevent cycles.

Steps:

  • Initialize queue with start nodes.
  • Process level by level.
  • Track visited nodes.

Example

Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]]

Python Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ans = [] if root is None: return ans q = deque([root]) ans = [] left = 1 while q: t = [] for _ in range(len(q)): node = q.popleft() t.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) ans.append(t if left else t[::-1]) left ^= 1 return ans

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy