Binary Tree Level Order Traversal
The problem
Section titled “The problem”You get the root of a binary tree. Return a list of lists: the first holds the root, the second holds its children left to right, the third holds the grandchildren, and so on. An empty tree gives an empty list.
[3, 9, 20, null, null, 15, 7] -> [[3], [9, 20], [15, 7]]Key insight
Section titled “Key insight”Recursion (DFS) dives to the bottom before it visits the neighbours, which is the wrong order for “row by row”. Breadth-first search visits nodes in exactly the order you want, and a queue gives you that: take a node from the front, push its children onto the back.
The only extra problem is knowing where one level ends. The trick: at the start of each
pass, the queue holds exactly the nodes of the current level. Read len(queue) once, then
process that many nodes. Everything they push is the next level, and waits for the next
pass.
Show solutionHide solution
from collections import deque
def level_order(root: TreeNode | None) -> list[list[int]]: result = [] queue = deque([root] if root else []) while queue: level = [] for _ in range(len(queue)): # freeze the size: exactly one level 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 resultexport function levelOrder(root: TreeNode | null): number[][] { const result: number[][] = []; let level: TreeNode[] = root ? [root] : []; while (level.length) { result.push(level.map((node) => node.val)); const next: TreeNode[] = []; for (const node of level) { if (node.left) next.push(node.left); if (node.right) next.push(node.right); } level = next; // the children of this level are the next level } return result;}import java.util.*;
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); Queue<TreeNode> queue = new ArrayDeque<>(); if (root != null) queue.add(root); while (!queue.isEmpty()) { List<Integer> level = new ArrayList<>(); for (int i = queue.size(); i > 0; i--) { // freeze the size: exactly one level TreeNode node = queue.poll(); level.add(node.val); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } result.add(level); } return result; }}Complexity
Section titled “Complexity”- Time: O(n) — each node is enqueued and dequeued once.
- Space: O(n) — the queue holds one whole level at a time, up to about n/2 nodes for the widest level, and the output itself stores all n values.
Watch out for
Section titled “Watch out for”- Freeze the level size before the inner loop. If you re-read
len(queue)while pushing children, levels bleed into each other. In Pythonrange(len(queue))does this for you. - Guard the empty tree. Don’t put
Nonein the queue; start with an empty queue when the root is missing, or you will readNone.val. - Use a real queue. In Python use
deque.popleft();list.pop(0)is O(n) per call. JavaScript arrays have the same problem withshift(), so the TypeScript solution builds each level as its own array instead: same BFS, no dequeue needed.
Variations
Section titled “Variations”Binary Tree Right Side View (LeetCode 199)
Section titled “Binary Tree Right Side View (LeetCode 199)”What you would see looking from the right. The trick: same level-by-level BFS, but keep only the last node of each level.
Binary Tree Zigzag Level Order Traversal (LeetCode 103)
Section titled “Binary Tree Zigzag Level Order Traversal (LeetCode 103)”Alternate direction each level. The trick: run the normal BFS, then reverse every other level’s list (or append to the front of it) before adding it to the result.
Binary Tree Level Order Traversal II (LeetCode 107)
Section titled “Binary Tree Level Order Traversal II (LeetCode 107)”Levels from the bottom up. The trick: run the same BFS and reverse the list of levels at the end. O(n).