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).
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Tree:
3
/ \
9 20
/ \
15 7
Level 0: [3]
Level 1: [9, 20]
Level 2: [15, 7]
Input: root = [1]
Output: [[1]]
Input: root = []
Output: []
Level order traversal is BFS (Breadth-First Search).
Key idea: Process nodes level by level using a queue.
We need to keep track of when one level ends and the next begins.
This is a BFS Tree Traversal problem with:
Handle Edge Case: If root is null, return empty list
Initialize:
Process Each Level:
Return result
Key Trick: Take snapshot of queue size at start of each level. This tells us exactly how many nodes are in current level.
result = []
queue = [root]
while queue:
level_size = len(queue) # Snapshot!
current_level = []
for i in range(level_size):
node = queue.pop(0)
current_level.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
result.append(current_level)
Time: O(n) where n = number of nodes
Space: O(w) where w = maximum width of tree
1import java.util.*;
2
3class TreeNode {
4 int val;
5 TreeNode left;
6 TreeNode right;
7 TreeNode() {}
8 TreeNode(int val) { this.val = val; }
9 TreeNode(int val, TreeNode left, TreeNode right) {
10 this.val = val;
11 this.left = left;
12 this.right = right;
13 }
14}
15
16class Solution {
17 public List<List<Integer>> levelOrder(TreeNode root) {
18 List<List<Integer>> result = new ArrayList<>();
19
20 if (root == null) {
21 return result;
22 }
23
24 Queue<TreeNode> queue = new LinkedList<>();
25 queue.offer(root);
26
27 while (!queue.isEmpty()) {
28 int levelSize = queue.size(); // Snapshot of current level size
29 List<Integer> currentLevel = new ArrayList<>();
30
31 // Process all nodes in current level
32 for (int i = 0; i < levelSize; i++) {
33 TreeNode node = queue.poll();
34 currentLevel.add(node.val);
35
36 // Add children for next level
37 if (node.left != null) {
38 queue.offer(node.left);
39 }
40 if (node.right != null) {
41 queue.offer(node.right);
42 }
43 }
44
45 result.add(currentLevel);
46 }
47
48 return result;
49 }
50}
51