Binary Tree Level Order Traversal
mediumNeetCode 150treesbfs
Problem
Given the root of a binary tree, return its node values grouped level by level from top to bottom, each level read left to right.
Examples
Input: [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Each inner list is one level.
Constraints
- • 0 <= number of nodes <= 2000
- • -1000 <= node value <= 1000
Hints(tap to reveal)
- 1. A queue processes nodes breadth first.
- 2. Process one full level at a time by tracking the queue size.
Optimal approach(spoiler)
- Seed a queue with the root if it exists.
- For each level, record the current queue size as the level width.
- Dequeue exactly that many nodes, collecting their values and enqueuing children.
- Append the collected values as one level.
- O(n) time, O(n) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor