Binary Tree Level Order Traversal

Mediumtreebreadth-first-searchqueue
Category: Trees
Companies that ask this question:
AmazonFacebookMicrosoftGoogleLinkedIn

Approach

Binary Tree Level Order Traversal

Problem Statement

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).

Examples

Example 1

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]

Example 2

Input: root = [1]
Output: [[1]]

Example 3

Input: root = []
Output: []

Intuition

Level order traversal is BFS (Breadth-First Search).

Key idea: Process nodes level by level using a queue.

  • Enqueue root
  • While queue not empty:
    • Process all nodes at current level
    • Add their children for next level

We need to keep track of when one level ends and the next begins.

Pattern Recognition

This is a BFS Tree Traversal problem with:

  • Queue-based approach
  • Level-by-level processing
  • Group nodes by depth

Approach

BFS with Queue

  1. Handle Edge Case: If root is null, return empty list

  2. Initialize:

    • Result list (list of levels)
    • Queue with root
  3. Process Each Level:

    • Get current level size (nodes in queue)
    • Create list for current level
    • For each node in this level:
      • Dequeue node
      • Add value to current level list
      • Enqueue left child (if exists)
      • Enqueue right child (if exists)
    • Add current level to result
  4. 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.

Why This Works

  • Queue ensures FIFO order (left to right)
  • Level size snapshot ensures we process exactly one level at a time
  • Children are queued for next iteration

Implementation Pattern

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)

Edge Cases

  • Empty tree
  • Single node
  • Complete binary tree
  • Skewed tree (all left or all right)
  • Tree with many levels

Complexity Analysis

  • Time: O(n) where n = number of nodes

    • Visit each node exactly once
    • O(1) work per node (enqueue/dequeue)
  • Space: O(w) where w = maximum width of tree

    • Queue holds nodes of current level
    • Maximum width can be O(n/2) ≈ O(n) for complete tree
    • For balanced tree: O(2^h) where h = height

Solution

java
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
Loading visualizer...