Back to LeetCode solutions

102. Binary Tree Level Order Traversal

Binary TreeBFSQueue
3 min read

Problem

Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level).

Explanation

Final solution: BFS with queue

I use a Queue to traverse the tree level by level. First, I handle the empty tree edge case by returning an empty list immediately. Then I start by adding the root node to the queue. The key insight is to process nodes in complete levels: before processing each level, I capture the current queue size, which tells me exactly how many nodes are in that level. I then loop that many times, polling each node, recording its value, and adding its children (left first, then right) to the queue for the next level. After processing all nodes in a level, I add that level's list to my result. This continues until the queue is empty, meaning I've visited every node exactly once. The BFS approach naturally produces the level-order traversal because the queue maintains the "next nodes to visit" in the correct left-to-right, level-by-level order.

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

Solution

Java
Tests
Input
root = [3, 9, 20, null, null, 15, 7]
Output
(waiting for execution)
Expected Output
[[3], [9, 20], [15, 7]]