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
Constraints
- 0 <= number of nodes <= 30,000.
- Each value is a whole number between -5,000 and 5,000.
- The tree can be one long chain.
Your answer must contain
- The simple method and its cost; the better method; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
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 rowsTime 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 [].