← Whiteboard questions

Binary Tree Level Order Traversal

List the values of a tree row by row

DSA, Medium, Trees

Which structure or algorithm, and what does it cost.

You get a binary tree tree. Your code may take the root node or the list. Each node has val, left and right, null when missing. Either is fine; no conversion is needed. The examples use a level-order list. It holds values row by row, left to right. Null marks a missing child. A missing node has no entries below it. An empty list is an empty tree. Return a list of lists. The first inner list holds the root, the next holds the nodes one step below it, and so on, each from left to right. An empty tree gives an empty list.

Examples

Input tree = [9, 4, 12, 2, null, 10, 15, null, null, null, 11]
Output [[9], [4, 12], [2, 10, 15], [11]]
Why the rows hold 1, 2, 3 and 1 nodes. The gaps in the input are not in the output.
Input tree = [1, null, 2, 3, 4, 5]
Output [[1], [2], [3, 4], [5]]
Why a missing node has no entries below it, so rows do not sit at fixed positions in the list.
Input tree = []
Output []
Why an empty tree has no rows.

Constraints

Your answer must contain

Target Aim for O(n) time.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Each output row holds the nodes at the same distance from the root. What links one row to the next?

Hint 2 the approach

The next row is made of the children of the nodes in this row, in the same left-to-right order. How do you collect them?

Hint 3 the key step

Hold the current row as a list. Save its values, then build the next row from the existing children of its nodes. Repeat until a row is empty.

Walkthrough

Full walkthrough brute force to best

Brute force

For each depth d, walk the whole tree and collect the nodes that sit at depth d, left to right. There are as many walks as the tree is deep, and each walk visits every node. A chain of n nodes makes n walks of n steps, so this is O(n^2) time.

Better method

Walk the tree once, depth first, carrying the depth. Append each value to the row for its depth, visiting left before right so each row stays in order. This is O(n) time, but the recursion is as deep as the tree and can overflow on a long chain.

Best method

Build the rows one at a time. The first row is the root. The next row is all the children of the nodes in the current row, taken in order, so left-to-right order is kept. Repeat until a row is empty. Every node enters exactly one row, so the work is linear. There is no recursion, so a deep chain is safe. This breadth-first pattern also answers questions about the widest row, the last node of a row, or the average of a row.

Hand trace

Run on [9, 4, 12, 2, null, 10, 15, null, null, null, 11]. The tree: 9 has children 4 and 12. Node 4 has a left child 2. Node 12 has children 10 and 15. Node 10 has a right child 11. Row 1 is [9]. Its children give row 2: [4, 12]. The children of 4 and 12 are 2, 10 and 15, so row 3 is [2, 10, 15]. Only node 10 has a child, 11, so row 4 is [11]. Row 5 would be empty, so we stop. The result is [[9], [4, 12], [2, 10, 15], [11]].

Code

def level_order(root):
    rows, row = [], [root] if root else []
    while row:
        rows.append([node.val for node in row])
        row = [child for node in row for child in (node.left, node.right) if child]
    return rows

Time and memory

O(n) time, because every node is put in one row and read once. O(w) extra memory for the current row, where w is the widest row, at most n.

Common mistakes

  • Mixing rows together. Keep the current row as its own list, so one pass over it makes exactly one output row.
  • Adding missing children to the next row. Add only children that exist, or the loop never ends.
  • Returning [[]] for an empty tree. An empty tree has no rows, so the answer is [].

Related problems

More Trees problems
Binary Tree Level Order Traversal: walkthrough and solution