Binary Tree Level Order Traversal

Medium

Topics
TreeBFS

Given the root of a binary tree, return its level-order traversal — a list of levels, each a list of node values from left to right. On this judge levels are shown separated by |.

Example 1

9315207
The answer groups nodes by level, one inner list each (the three shades mark the first three levels). A plain queue visits nodes in the right order but loses the grouping; draining exactly the current queue length before moving on restores it.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2

empty tree
Input:  root = []
Output: []

Constraints

  • 0 <= number of nodes <= 2000
  • -1000 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

A breadth-first traversal naturally visits the tree level by level. Process the queue one full level at a time by capturing its size before the inner loop.

Approach

  1. Push the root; if null, return empty.
  2. While the queue is non-empty, record its current size — that is one level.
  3. Pop exactly that many nodes into the current level list, enqueueing their children.

Dry Run

tree 3 9 20 null null 15 7
      3
     / \
    9   20
       /  \
      15   7
The queue is shared across levels, so the level boundary has to be captured
before any children are added:
  snapshot len(q)=1   pop [3]        enqueue 9, 20   queue [9, 20]
  snapshot len(q)=2   pop [9, 20]    enqueue 15, 7   queue [15, 7]
  snapshot len(q)=2   pop [15, 7]    enqueue nothing queue []
answer [3] | [9, 20] | [15, 7]
That snapshot is the only interesting line in the algorithm. Read the length
live -- `while q` on the inner loop -- and the children appended during a level
get consumed by the same level, which collapses the whole tree into one list:
[[3, 9, 20, 15, 7]]. The levels do not just shift, they dissolve.
Note that nulls are never enqueued; the `if node.left` guards keep them out. That
is why level 3 contains 15 and 7 rather than four entries with two holes -- the
output has no notion of position within a level, only membership.

Complexity

  • Time — O(n): each node is enqueued and dequeued once.
  • Space — O(n): the queue can hold a full level.

Common Pitfalls

  • Snapshot the queue length before the inner loop, since you keep adding children to the same queue.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def levelOrder(self, root):
        if not root: return []
        from collections import deque
        res=[]; q=deque([root])
        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)
            res.append(level)
        return res
SensAI
Beta
Tap the mic to stop voice mode