#103

Binary Tree Zigzag Level Order Traversal

Medium
TreeBreadth-First SearchBinary TreeBreadth-First Search (BFS)Deque for efficient insertion/removal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use a queue for level order traversal and a flag to alternate the order of insertion. This way, we avoid reversing the list at each level, making it more efficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue and add the root node.
  2. 2Step 2: Use a boolean flag to track the direction of insertion.
  3. 3Step 3: For each level, collect values in the appropriate order based on the flag.
solution.py25 lines
1# Full working Python code
2from collections import deque
3
4def zigzagLevelOrder(root):
5    if not root:
6        return []
7    result = []
8    queue = deque([root])
9    left_to_right = True
10    while queue:
11        level_size = len(queue)
12        current_level = deque()
13        for _ in range(level_size):
14            node = queue.popleft()
15            if left_to_right:
16                current_level.append(node.val)
17            else:
18                current_level.appendleft(node.val)
19            if node.left:
20                queue.append(node.left)
21            if node.right:
22                queue.append(node.right)
23        result.append(list(current_level))
24        left_to_right = not left_to_right
25    return result

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the storage of nodes in the queue.

  • 1Using a deque allows for efficient insertion at both ends, which is crucial for zigzag traversal.
  • 2Maintaining a boolean flag to track the direction of traversal simplifies the logic.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.