AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Binary Tree Level Order Traversal

The key idea

Process the tree one full level at a time using a queue. Before each round, record how many nodes are currently in the queue: that count is exactly the size of the current level, so you can pop precisely that many nodes into one group before moving on.

Problem

Given the root of a binary tree, return the level order traversal of its nodes' values. A level order traversal visits the nodes level by level, from top to bottom, and within each level it reads them from left to right. The result groups the values of each level into its own list, so the outer list holds one inner list per level, ordered from the root level downward.

Constraints

Examples

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

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems