AceYourInterviews
Checking sign-in…

81. Binary Tree Level Order Traversal

CoreFreeze the current BFS frontier before adding the next level

Visit the tree one depth at a time, beginning with the root. Return a separate list for every depth, preserving left-to-right order within a level.

The output groups nodes by distance from the root. Do not mix levels or return a depth-first traversal.

Example 1

Input

[3,9,20,null,null,15,7]

Output

[[3],[9,20],[15,7]]

Explanation: Children of earlier parents enter the FIFO first; left enters before right.

Example 2

Input

[1,null,2,null,3]

Output

[[1],[2],[3]]

Explanation: One value per level on a chain; queue size is not tree height.

Constraints

  • 0 <= node count per tree <= 105
  • -231 <= node.value <= 231 - 1
  • Each input is a proper binary tree: no cycles or shared child nodes. Null trees are permitted.
Hints
Hint 1

A queue visits nodes in nondecreasing depth.

Hint 2

How many nodes belong to the level before you enqueue any children?

Hint 3

Capture that count, remove exactly that many, then store the fresh row.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Freeze level size before adding children

[3,9,20,null,null,15,7]
[[3],[9,20],[15,7]]