Problem 444231 · medium · Level 04 Non-Linear Data Structures

Floor-by-Floor Roll Call

binary tree · BFS · queue

Depth-first recursion visits a tree branch by branch. Breadth-first search (BFS) instead visits it level by level, which is exactly what you need to answer questions like "which nodes are at depth 2?".

Picture the tree as a building with the root alone on the top floor, its children one floor down, their children below that, and so on. Write level_order(root) that takes the roll call floor by floor: return one inner list per floor, top floor first, each holding that floor's values from left to right. An empty tree gives [].

Examples

      8
     / \
    4   11
   /   /  \
  2   9    14

Input:  root = [8, 4, 11, 2, None, 9, 14]
Output: [[8], [4, 11], [2, 9, 14]]
    1
   / \
  2   3
 /     \
4       5

Input:  root = [1, 2, 3, 4, None, None, 5]
Output: [[1], [2, 3], [4, 5]]
Input:  root = []
Output: []

Constraints

  • 0 <= number of nodes <= 1000

Goals

  • Traverse a tree breadth-first with a deque
  • Process one level at a time by snapshotting the queue length
  • Build a list of lists as output
Starting Python…