↓Skip to main content
  1. LeetCode/

LeetCode 103: Binary Tree Zigzag Level Order Traversal

·1 min· ·
LeetCode Medium Tree Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-18

  • Submissions: Accepted (first try)

Approach
#

Collect level by level (Tree Template 2): levels 0, 2, 4, … left to right, and levels 1, 3, 5, … reversed. The order of building the next level stays the same; only the recorded direction changes.

My Solution
#

class Solution:
    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        res, level = [], [root] if root else []
        while level:
            vals = [n.val for n in level]
            res.append(vals if len(res) % 2 == 0 else vals[::-1])
            level = [c for n in level for c in (n.left, n.right) if c]
        return res

Complexity
#

Time O(n), space O(w).

Mistakes to Avoid
#

  • Reverse only the recorded values, not the order of building the next level.

Interview Explanation
#

I run a normal BFS and reverse the recorded values on odd levels, leaving the next-level order unchanged. Time O(n).

Related

LeetCode 107: Binary Tree Level Order Traversal II
·1 min
LeetCode Medium Tree Breadth-First-Search Binary-Tree
LeetCode 107 note: a normal level-order traversal reversed at the end gives bottom-up order
LeetCode 102: Binary Tree Level Order Traversal
·1 min
LeetCode Medium Tree Breadth-First-Search Binary-Tree
LeetCode 102 note: BFS one whole level at a time, building the next level from the current one; an empty tree returns an empty list
LeetCode 1448: Count Good Nodes in Binary Tree
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1448 note: pass the path maximum down during DFS; a node is good when its value is at least that maximum
LeetCode 199: Binary Tree Right Side View
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 199 note: in a level-order traversal, each level’s rightmost node is what you see from the right
LeetCode 1379: Find a Corresponding Node of a Binary Tree in a Clone of That Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1379 note: walk both trees in lockstep; when the original reaches target, the clone’s node at the same position is the answer, comparing node identity
LeetCode 113: Path Sum II
·2 mins
LeetCode Medium Backtracking Tree Depth-First-Search Binary-Tree
LeetCode 113 note: backtrack with the current path and store a copy at a leaf whose total matches; values can be negative, so no early pruning