Tensorum
LeetCode 103 · BFS / Level Order

Binary Tree Zigzag Level Order Traversal

LeetCode 103 · Medium · solution, intuition & step-by-step walkthrough

BFS + flip direction per level.

MediumTreeBreadth-First SearchBinary Tree
1 msruntime · beats 24%
52.1 MBmemory · beats 100%
1approach
5accepted runs · last 15 Dec 2024

This is how I solved Binary Tree Zigzag Level Order Traversal (LeetCode 103), a medium problem from the BFS / Level Order pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Normal level-order BFS, but alternate direction each level: on left-to-right levels append values, on right-to-left levels insert them at the front.

Approach

  1. 1

    BFS with a level marker.

  2. 2

    Flip leftToRight at every marker.

  3. 3

    Append or prepend the value depending on direction.

How I solved it

BFS with direction flagPythonO(n) time
class Solution:
    def zigzagLevelOrder(self, root):
        if root is None:
            return []
        res = [[]]
        queue = [root, "\n"]
        leftToRight = True
        while len(queue) > 1:
            node = queue.pop(0)
            if node is None:
                continue
            if node == "\n":
                queue.append("\n")
                res.append([])
                leftToRight = not leftToRight
                continue
            else:
                if leftToRight:
                    res[-1].append(node.val)
                else:
                    res[-1].insert(0, node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return res
Loading the step-through…

Binary Tree Zigzag Level Order Traversal — FAQ

What is the intuition behind Binary Tree Zigzag Level Order Traversal?

Normal level-order BFS, but alternate direction each level: on left-to-right levels append values, on right-to-left levels insert them at the front.

How do you solve Binary Tree Zigzag Level Order Traversal (LeetCode 103)?

1. BFS with a level marker. 2. Flip leftToRight at every marker. 3. Append or prepend the value depending on direction.

What is the time and space complexity of Binary Tree Zigzag Level Order Traversal?

Time: O(n). Space: O(n). (Accepted approach: BFS with direction flag.)

What are common mistakes in Binary Tree Zigzag Level Order Traversal?

unshift / insert(0) is O(k); a deque per level avoids it.