InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Binary Tree Level Order Traversal

medium Original ↗ 00:00

Problem

Given the root of a binary tree, return its level order traversal: a list of lists, where the first inner list holds the values at depth 0 (the root), the second holds depth 1 left-to-right, and so on down the tree.

Examples

Example 1

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

Depth 0 is just the root 3; depth 1 is 9 then 20; depth 2 is 20’s children 15 then 7.

Example 2

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

A single node is one level.

Example 3

Input: root = []
Output: []

An empty tree has no levels.

Constraints

  • The number of nodes is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Expected: visit every node once — O(n) time — while grouping output by depth.

Think about it first

Hint 1 Which traversal visits nodes in order of increasing distance from the root, and what data structure drives it?
Hint 2 A queue gives you nodes in level order, but the output needs level *boundaries*. What quantity, read at the right moment, tells you where one level ends?
Hint 3 At the start of each round, `len(queue)` is the size of the current level. Pop that many nodes into one list while enqueueing their children; the children are the next level. (Alternatively: DFS carrying the depth, appending to `result[depth]`.)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug