Floor-by-Floor Roster

Medium · Trees & BSTs · about 15 min

An office seats its org chart by depth: the top person on floor 1, their direct reports on floor 2, and so on. The tree is a level-order list: the root first, then each node's left and right child in turn, with None (Python) / null (JavaScript) for a missing child. A build(level) helper in the starter turns it into nodes with .val, .left and .right.

Return the roster as a list of floors, top floor first. Each floor is the list of values on that level, left to right. An empty chart gives [].

  • Up to 10,000 people, values are any integers.

Examples:

floor_lists([3, 9, 20, None, None, 15, 7]) → [[3], [9, 20], [15, 7]]

floor_lists([1, 2, None, 3, None, 4]) → [[1], [2], [3], [4]]

Hints

  • A queue (or a list for the current level) gives you nodes in the order they were discovered.
  • Process one whole level at a time so you know where each floor ends.
  • Add the left child before the right child to keep the left-to-right order.

Learn the pattern first: the Trees & BSTs lesson.

More Trees & BSTs problems