LeetCode ยท #102

Binary Tree Level Order Traversal Solution

Given the root of a binary tree, return the level order traversal โ€” values grouped by level, left to right.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Medium

๐Ÿ”—

LeetCode

Problem #102

๐Ÿ—๏ธ

Pattern

BFS โ€” queue with level grouping

Given the root of a binary tree, return its level order traversal as a list of lists โ€” each inner list contains the values of nodes at that depth level, from left to right.

Example
Input: 3 / \ 9 20 / \ 15 7 Output: [[3], [9, 20], [15, 7]]
Constraints
โ€ข 0 โ‰ค number of nodes โ‰ค 2000 โ€ข -1000 โ‰ค Node.val โ‰ค 1000
02
Section Two ยท Approach 1

DFS with Depth Tracking โ€” O(n)

DFS (preorder), passing the current depth. Use a list of lists where depth is the index. Append values at their depth. Works but doesn't process nodes in a natural level-by-level order.

03
Section Three ยท Approach 2

BFS with Queue โ€” O(n)

Use a queue. At each level, process all nodes currently in the queue (that's one level), collect their values, and enqueue their children. The queue naturally separates levels.

๐Ÿ’ก Mental model: Imagine a stadium where each row is a level. You photograph row 1 (just the root), then row 2 (root's children), then row 3, etc. At each row, you snap all people in that row before moving to the next. The queue holds the current row.
Algorithm
  • Step 1: If root is null, return empty list.
  • Step 2: Initialize queue with root.
  • Step 3: While queue not empty:
  • levelSize = queue.size() โ€” snapshot current level count.
  • Process exactly levelSize nodes: dequeue, collect value, enqueue children.
  • Add collected values as a new level to result.
๐ŸŽฏ Key trick โ€” levelSize snapshot:
  • Before processing, capture queue.size(). This is how many nodes belong to the current level.
  • New children enqueued during this loop belong to the next level and won't be processed until the next iteration.
04
Section Four ยท Trace

Visual Walkthrough

BFS level-by-level โ€” queue snapshot per level
TREE 3 Level 0 9 20 Level 1 15 7 Level 2 QUEUE STATE AT EACH LEVEL Level 0 queue=[3], size=1 Process 3 โ†’ enqueue 9, 20 [3] Level 1 queue=[9,20], size=2 Process 9,20 โ†’ enqueue 15, 7 [9, 20] Level 2 queue=[15,7], size=2 Process 15, 7 โ†’ no children โ†’ done [15, 7] RESULT [[3], [9, 20], [15, 7]] โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” BFS with Queue
import java.util.*; class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int levelSize = queue.size(); List<Integer> level = new ArrayList<>(); for (int i = 0; i < levelSize; i++) { TreeNode node = queue.poll(); level.add(node.val); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } result.add(level); } return result; } }
Python โ€” BFS with deque
from collections import deque class Solution: def levelOrder(self, root): if not root: return [] result = [] queue = deque([root]) while queue: level = [] for _ in range(len(queue)): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level) return result
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
BFS QueueO(n)O(n) โ€” queue holds widest level
DFS + depth indexO(n)O(h) stack + O(n) result
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
EmptynullReturn []. Check before enqueuing.
Single node[1]Result: [[1]]. One level.
Skewed left1โ†’2โ†’3Result: [[1],[2],[3]]. One node per level.
Complete treeFull binary treeWidest level has n/2 nodes โ†’ queue peaks at O(n).
โš  Common Mistake: Not capturing queue.size() before the for-loop. If you use queue.size() directly in the loop condition, it changes as you add children โ€” mixing levels in the same list.

โ† Back to Trees problems