Command Palette

Search for a command to run...

Problem 16.7 · Binary TreesMedium

Binary Tree Level Order Traversal

What it teaches: The BFS template with level sizes.

Practise it on judges as “Binary Tree Level Order Traversal”.

The problem

Return the node values level by level, left to right.

Example 1

Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]

Constraints

  • 0 ≤ nodes ≤ 2000

Pattern clues in the wording

  • → "Level by level"

These clues point to Tree BFS (Level Order): Process the tree level by level with a queue, handling exactly one level per loop.

Stuck? Take one hint at a time

Solution.java · starter
import java.util.*;

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        return new ArrayList<>();
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
root = [3,9,20,null,null,15,7]
[[3],[9,20],[15,7]]
2
root = [1]
[[1]]
3
root = []
[]

From slow to fast

Approaches

1

BFS with a queue

Time O(n) Space O(width)

For each level, poll size nodes into a list and offer their children.

Approach 1
import java.util.*;

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> out = new ArrayList<>();
        if (root == null) return out;
        Queue<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        while (!q.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            for (int size = q.size(); size > 0; size--) {
                TreeNode n = q.poll();
                level.add(n.val);
                if (n.left != null) q.offer(n.left);
                if (n.right != null) q.offer(n.right);
            }
            out.add(level);
        }
        return out;
    }
}

Verdict: Standard.

Before you submit

Edge cases and common mistakes

Test these inputs

  • Empty tree → []
  • Skewed tree

Mistakes people make

  • Offering null children.

Interview

Follow-up questions

How do you produce zigzag order?