0:00 / 0:00

Read a binary tree one level at a time. Keep a queue, and each round empty exactly the nodes that were in it when the round began.

▼

The problem

LeetCode 102, Binary Tree Level Order Traversal (Medium). Given the root of a binary tree, return its node values level by level, top to bottom and left to right within a level, as a list of lists.

Example (levels of uneven width, 1 / 2 / 3 / 2): root 3; children 9 and 20; then 4 (left child of 9), 15 and 7 (children of 20); then 6 (right child of 4) and 2 (left child of 7).

from collections import deque

def level_order(root):
    out = []
    q = deque([root] if root else [])
    while q:
        level = []
        for _ in range(len(q)):
            node = q.popleft()
            level.append(node.val)
            for kid in (node.left, node.right):
                if kid:
                    q.append(kid)
        out.append(level)
    return out
TRY IT ON LEETCODE ▶

The solution

from collections import deque

def level_order(root):
    out = []
    q = deque([root] if root else [])
    while q:
        level = []
        for _ in range(len(q)):
            node = q.popleft()
            level.append(node.val)
            for kid in (node.left, node.right):
                if kid:
                    q.append(kid)
        out.append(level)
    return out

Transcript

Binary Tree Level Order Traversal. Given the root of a binary tree, return its values level by level: top to bottom, and left to right within each level, as a list of lists.

Take this tree. Three is on top. Below it, nine and twenty. Then four, fifteen and seven. And at the bottom, six and two. Four levels, so the answer holds four lists.

The usual way to walk a tree is depth-first: dive down one branch before the next. Here that visits three, nine, four, six, and only then climbs back up to twenty. The levels come out mixed.

Breadth-first search goes floor by floor, using a queue: a line of nodes waiting their turn. Children join at the back, and we always take from the front, so a whole level leaves before the level below it.

Where does one level end? Here's the trick: at the start of each round, the line holds exactly one level, and nothing else. So count the line. Take exactly that many from the front, record their values, and send their children to the back.

Let's run it. The line starts with three. Round one counts one: three leaves, and nine and twenty join. Round two counts two: nine sends four, twenty sends fifteen and seven. Round three counts three: four sends six, fifteen has no children, seven sends two. Round four counts two: six and two have no children, so the line is empty.

In code, a double-ended queue holds the line, starting with the root. While it's not empty, start a new level and loop length of the queue times: pop from the left, save the value, append any children. Then add the level to the output.

Every node joins the line once and leaves once, so the time is O of n. The line only ever holds the rest of one level plus part of the next, so the space is O of the width.

Count the line, clear the floor, repeat. That's Level Order Traversal.