Floor-by-Floor Listing

MediumTrees

Problem

An org chart is stored as a binary tree. HR wants the staff listed floor by floor: the root on the first floor, its children on the second, and so on, each floor read from left to right.

Given the root, return a list of floors, where each floor is the list of values on that level from left to right.

Example 1

Input:
root = [3, 9, 20, null, null, 15, 7]
Output:
[[3], [9, 20], [15, 7]]

Example 2

Input:
root = [1]
Output:
[[1]]

Example 3

Input:
root = []
Output:
[]

Constraints

  • 0 ≤ number of nodes ≤ 10^4
  • -1000 ≤ node.val ≤ 1000

Hint

Show the first hint

Which data structure visits nodes in order of distance from the root?

Walkthrough

How to approach it

01Clarify before coding

  • Within a floor, left to right? Yes.
  • Empty tree? Return an empty list, not [[]].
  • Do missing children leave gaps? No, floors list only existing nodes.

02Brute force

Do a DFS that records (depth, value) for each node, then group values by depth.

Cost: O(n) time if grouped by appending to a list per depth, which is already fine; the BFS version is simply the natural fit and avoids recursion depth issues.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.