InterviewPrepKit

Home / Coding / Trees

Binary Tree Level Order Traversal

medium Original ↗
Solving tips
  • This is the canonical BFS-by-level problem: use a queue and snapshot level_size = len(queue) at the top of each round before popping.
  • Pop exactly level_size nodes into one list while enqueueing their children, which are precisely the next level.
  • Alternative: DFS carrying depth, appending each value to result[depth] and creating a fresh list when depth == len(result); preorder keeps each level left-to-right.
  • Handle the empty tree (return []) and never re-read len(queue) mid-loop; target O(n) time and O(n) space.

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 naturally 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, snapshotted at the right moment, tells you exactly where one level ends?
Hint 3 At the top of each round, `len(queue)` is exactly the size of the current level. Pop that many nodes into one list, enqueueing their children — the children are precisely the next level. (Alternatively: DFS carrying the depth, appending to `result[depth]`.)
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.