⚡Flashcard Drill➔
NeetCode #434LC-103MediumTrees
← Back to All Problems

#434 · #103 · Binary Tree Zigzag Level Order Traversal(二叉树的锯齿形层序遍历)

📌 Problem Statement & Constraints

Given the root of a binary tree, return its zigzag level-order traversal: levels alternate between left-to-right and right-to-left, starting with left-to-right. Constraints: the number of nodes is in [0, 2000], -100 <= Node.val <= 100.

💡 Core Algorithmic Approaches

  1. A standard BFS collects each level's values left to right.
  2. Reverse the collected level on every other level (the odd-indexed ones).
  3. Flipping a boolean flag per level tracks the direction.
  4. An alternative uses a deque and appends to the front or back depending on the direction, avoiding the reversal.

💻 Benchmark Python3 Implementation

class Solution:
    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        from collections import deque
        if not root:
            return []
        res = []
        q = deque([root])
        left_to_right = True
        while q:
            n = len(q)
            level = []
            for _ in range(n):
                node = q.popleft()
                level.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            if not left_to_right:
                level.reverse()            # flip the even levels
            res.append(level)
            left_to_right = not left_to_right
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): every node is visited once and each level is reversed at most once.
💾 Space Complexity
O(w) for the widest level.

⚠️ Interview Pitfalls & Follow-ups

  • Reversing the wrong levels: the first level (index 0) is left-to-right, so odd indices are reversed.
  • Reversing the children before pushing them: that changes the traversal order rather than the output order and breaks the next level.
  • Using a single level.reverse() on the queue: the queue must not be mutated.
  • Forgetting the empty-tree case: an empty tree has an empty result.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

二叉树的锯齿形层序遍历

给你二叉树的根节点 root,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。约束:树中节点数目在范围 [0, 2000] 内;-100 ≤ Node.val ≤ 100。

核心要点

  • BFS + 按层反转(标准解) :正常层序遍历,维护一个方向标志;偶数层(0-based)从左到右,奇数层反转后再加入结果。
  • 为什么用「先收集再反转」而非「按方向入队」 :反转列表是 O(k),总代价与层节点数同阶;而改变入队顺序会让子节点的入队顺序也受影响,容易出错。
  • 复杂度 :O(n) 时间、O(w) 空间。

常见陷阱

  • 通过改变入队顺序来实现反转 :会打乱子节点的入队顺序,导致下一层也出错。必须「先按标准顺序收集,再反转本层结果」。
  • 方向标志初值设为 False :第一层(根)应从左到右,初值应为 True。
  • 忘记翻转方向标志 :每层结束后必须 left_to_right = not left_to_right 。

参考实现

from collections import deque

class Solution:
    def zigzagLevelOrder(self, root: 'TreeNode') -> list[list[int]]:
        if not root:
            return []
        res = []
        q = deque([root])
        left_to_right = True
        while q:
            level = []
            for _ in range(len(q)):
                node = q.popleft()
                level.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            if not left_to_right:
                level.reverse()             # 奇数层反转
            res.append(level)
            left_to_right = not left_to_right
        return res