Full answer
Problem
Given the root of a binary tree, return a list of levels, each holding that level's values from left to right.
Example: 3 -> 9, (20 -> 15, 7) gives [[3], [9, 20], [15, 7]]. Zigzag order gives [[3], [20, 9], [15, 7]], and the right-side view gives [3, 20, 7].
Constraints: 0 to 2,000 nodes; values are any integers.
Brute force
Compute the height h, then for each depth d run a separate DFS that collects nodes at depth d. That is O(n * h) time, O(n^2) on a chain.
Optimal approach
BFS with a deque. While the queue is not empty, take size = len(q), pop size nodes, append their values to a new list, and push their non-null children. Append the list to the result.
Variants are post-processing steps: reverse odd-indexed levels for zigzag; take level[-1] for the right-side view.
Why it works
BFS visits nodes in order of distance from the root. At the start of each round the queue holds exactly the nodes of one level, because all nodes of the previous level were popped in the previous round and only their children were pushed. Freezing len(q) before the inner loop keeps children from being mixed into the current level.
Complexity
O(n) time: each node enters and leaves the queue once. O(w) extra space for the queue, where w is the maximum width; output is O(n).
Code
from collections import deque
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def level_order(root):
"""Return values level by level. BFS with a queue; O(n) time, O(width) space."""
if root is None:
return []
levels, q = [], deque([root])
while q:
level = []
for _ in range(len(q)): # exactly the nodes of the current level
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
levels.append(level)
return levels
def zigzag(root):
return [lvl if i % 2 == 0 else lvl[::-1] for i, lvl in enumerate(level_order(root))]
def right_side_view(root):
return [lvl[-1] for lvl in level_order(root)]
def level_order_dfs(root):
"""Reference: DFS that records depth."""
out = []
def walk(n, d):
if n:
if d == len(out):
out.append([])
out[d].append(n.val)
walk(n.left, d + 1)
walk(n.right, d + 1)
walk(root, 0)
return out
if __name__ == "__main__":
t = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
assert level_order(t) == level_order_dfs(t) == [[3], [9, 20], [15, 7]]
assert zigzag(t) == [[3], [20, 9], [15, 7]]
assert right_side_view(t) == [3, 20, 7]
assert level_order(None) == [] and level_order(TreeNode(1)) == [[1]]
lopsided = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
assert right_side_view(lopsided) == [1, 3, 4]
print("all tests passed")Save as b54_level_order.py and run python3 b54_level_order.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty tree returns []. Single node. A lopsided tree where the right-side view must show a left node at the deepest level (the test with 1 -> (2 -> 4), 3 returns [1, 3, 4]). Deep chains are fine because BFS does not recurse.
Pattern
Level-by-level BFS using the queue size as a boundary. The same skeleton solves minimum depth, average of levels, connecting next pointers, and multi-source grid problems such as rotting oranges.
from collections import deque
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def level_order(root):
"""Return values level by level. BFS with a queue; O(n) time, O(width) space."""
if root is None:
return []
levels, q = [], deque([root])
while q:
level = []
for _ in range(len(q)): # exactly the nodes of the current level
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
levels.append(level)
return levels
def zigzag(root):
return [lvl if i % 2 == 0 else lvl[::-1] for i, lvl in enumerate(level_order(root))]
def right_side_view(root):
return [lvl[-1] for lvl in level_order(root)]
def level_order_dfs(root):
"""Reference: DFS that records depth."""
out = []
def walk(n, d):
if n:
if d == len(out):
out.append([])
out[d].append(n.val)
walk(n.left, d + 1)
walk(n.right, d + 1)
walk(root, 0)
return out
if __name__ == "__main__":
t = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
assert level_order(t) == level_order_dfs(t) == [[3], [9, 20], [15, 7]]
assert zigzag(t) == [[3], [20, 9], [15, 7]]
assert right_side_view(t) == [3, 20, 7]
assert level_order(None) == [] and level_order(TreeNode(1)) == [[1]]
lopsided = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
assert right_side_view(lopsided) == [1, 3, 4]
print("all tests passed")BFS with a frozen level size, plus zigzag and right-side view, cross-checked against a depth-tracking DFS.
Complexity
Time: O(n). Space: O(w) queue plus O(n) output. For a complete tree the last level holds about n/2 nodes, so queue space can be O(n).
By level
Fresher: Writes the BFS with the level-size loop and traces it on a small tree. Explains why a deque is used instead of a list.
Mid: Adapts the same code to zigzag, right-side view and bottom-up order without rewriting the traversal. Compares the BFS and depth-tagged DFS approaches.
Senior: Discusses memory on very wide trees and when a DFS with depth tags is cheaper. Relates level order to batch processing by distance, such as layered dependency resolution or friend-of-friend expansion in graphs.
Key points
- Freeze len(q) to separate levels
- Each node enqueued and dequeued once
- Zigzag = reverse odd levels
- Right-side view = last of each level
- DFS with a depth index gives the same groups
Common mistakes
- Using len(q) inside the loop so it changes as children are pushed
- Using a list with pop(0), which is O(n) per pop
- Pushing None children and then crashing on .val
- Reversing the queue for zigzag instead of the output
Follow-ups
- How do you return levels bottom-up?
- How would you connect each node to its right neighbour on the same level?
- Can this run with O(1) extra space on a perfect tree?
Tips
- Mention collections.deque for O(1) pops
- Show how a variant is just post-processing
- State space in terms of width
Evaluation rubric
- Correct grouping by level
- Uses an O(1)-pop queue
- Handles variants
- Correct complexity