Binary Tree Level Order Traversal (LeetCode 102): Solution and Explanation
Given the root of a binary tree, return its node values grouped by depth: the root's value first, then all values on the second level from left to right, then the third level, and so on. The output is a list of lists, one inner list per level.
Watch it run step by step
Try your own input and write the code →Intuition
Depth-first traversals like preorder or inorder dive down one branch before touching the next, so values from different depths come out interleaved. You could still fix that by passing the depth into a recursive call and appending each value to res[depth], but the problem is really asking for breadth-first order, so a queue is the natural tool.
A queue processes nodes in the order they were discovered. Start with the root; when you pop a node, push its children onto the back. Because all children of level d are pushed before any node of level d plus one is popped, the queue naturally holds the tree one level at a time. The only extra question is how to tell where one level ends and the next begins.
The answer is to take a snapshot of the queue's length at the start of each round. Exactly that many nodes belong to the current level, so you pop that many, collect their values into one list, and let their children pile up behind them for the next round. The reference code also pushes None children and simply skips them when popped, which keeps the loop body short at the cost of a few extra queue entries.
Approach: Breadth-first search with level-size snapshots
- Create an empty result list
resand a dequeqcontaining the root. - While the queue is not empty, record
qLen = len(q), the number of entries in the current level. - Pop exactly
qLenentries. For each one that is not None, append its value toleveland push its left and right children, even if they are None. - After the inner loop, append
leveltoresonly if it is non-empty, which filters out rounds made up entirely of None placeholders. - Return
resonce the queue is drained. An empty tree starts with[None], produces an empty level, and returns [].
Step-by-step example
root = [3,9,20,null,null,15,7]
- The queue starts as [3]. Round one pops 3, records [3], and pushes 9 and 20.
- Round two has
qLen2. Popping 9 pushes two None children, and popping 20 pushes 15 and 7. The level is [9,20]. - Round three has
qLen4: None, None, 15 and 7. The two None entries are skipped, while 15 and 7 are recorded and each pushes two None children. The level is [15,7]. - Round four pops four None entries, so
levelstays empty and is not added. - The queue is empty, and the result is [[3],[9,20],[15,7]].
Code: Python, Java, C++
1class Solution:
2 def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
3 res = []
4 q = collections.deque()
5 q.append(root)
6
7 while q:
8 qLen = len(q)
9 level = []
10 for i in range(qLen):
11 node = q.popleft()
12 if node:
13 level.append(node.val)
14 q.append(node.left)
15 q.append(node.right)
16 if level:
17 res.append(level)
18 return res1class Solution {
2 public List<List<Integer>> levelOrder(TreeNode root) {
3 List<List<Integer>> res = new ArrayList<>();
4 Queue<TreeNode> q = new LinkedList<>();
5 if (root != null) q.add(root);
6
7 while (!q.isEmpty()) {
8 int len = q.size();
9 List<Integer> level = new ArrayList<>();
10 for (int i = 0; i < len; i++) {
11 TreeNode node = q.poll();
12 level.add(node.val);
13 if (node.left != null) q.add(node.left);
14 if (node.right != null) q.add(node.right);
15 }
16 res.add(level);
17 }
18 return res;
19 }
20}1class Solution {
2public:
3 vector<vector<int>> levelOrder(TreeNode* root) {
4 vector<vector<int>> res;
5 queue<TreeNode*> q;
6 if (root) q.push(root);
7
8 while (!q.empty()) {
9 int len = q.size();
10 vector<int> level;
11 for (int i = 0; i < len; i++) {
12 TreeNode* node = q.front();
13 q.pop();
14 level.push_back(node->val);
15 if (node->left) q.push(node->left);
16 if (node->right) q.push(node->right);
17 }
18 res.push_back(level);
19 }
20 return res;
21 }
22};Time and space complexity
O(n)
Every real node is pushed and popped once, and each one adds at most two None placeholders, so the total number of queue operations is still linear in n.
O(n)
The queue can hold an entire level at once. In a complete binary tree the last level has about n / 2 nodes, and the output itself stores all n values.
Other approaches
DFS with a depth parameter (time O(n), space O(h))
Recurse with (node, depth). When depth equals len(res), append a new empty list, then add the value to res[depth]. Visiting left before right keeps each level ordered left to right, and the stack only grows to the tree height.
BFS that skips null children (time O(n), space O(n))
Only push a child when it exists, which avoids the None entries and the empty-level check. It is the same algorithm with a slightly smaller queue and needs an explicit early return for an empty root.
Common mistakes
- Reading
len(q)inside the inner loop instead of saving it first. The queue grows as children are pushed, so the level boundary gets lost. - Using a Python list with
pop(0)instead ofcollections.deque. Popping from the front of a list is O(n), which makes the traversal quadratic. - Pushing None children but forgetting to filter them or to skip empty levels, which produces a trailing empty list or a crash on
None.val. - Returning
[[]]for an empty tree. The correct answer is an empty list.
Frequently asked questions
BFS or DFS for level order traversal?
BFS is the natural fit because a queue already processes nodes level by level. DFS also works if you pass the depth and append into res[depth], and it can use less memory on wide, shallow trees.
How do you know where each level ends in BFS?
Capture the queue length at the start of each round. That count is exactly the number of nodes on the current level, so popping that many entries processes one level and leaves the next level in the queue.
What is the space complexity of level order traversal?
O(n). The queue can hold up to roughly half of the nodes when the bottom level of a complete tree is reached, and the output list stores every value.