Binary Tree Level Order Traversal

Node values of a binary tree grouped by level, from left to right

MediumTreesBFS

Given the root of a binary tree, return its node values level by level, from left to right.

Examples

Example 1

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

Example 2

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

Constraints

  • 0 ≤ nodes ≤ 10⁴

Implementation Notes

  • A normal BFS queue works.
  • Remember to separate each level's nodes before continuing.

Hints

Show hint 1

Use a queue and process nodes level by level, capturing the queue size before each round.

Show hint 2

Alternatively, use DFS with depth tracking to append values into level-indexed arrays.

Follow-up questions

What an interviewer might ask once you have a working solution.

  • How would you return a zig-zag (alternating direction) traversal?
  • Can you compute averages per level instead of raw values?

Practice this with an AI interviewer

Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.

Start this problem