Binary Tree Level Order Traversal

Free with account Updated Nov 19, 2026 · 4 min read
On this page

    Problem statement

    Given the root of a binary tree, return its values level by level: a list of lists, where each inner list holds one level's values from left to right.

    The template for every "by level" tree question: right side view, zigzag order, averages per level, minimum depth. The only real trick is knowing where one level ends. Original problem: LeetCode 102.

    Example

    The root 3 is level one, 9 and 20 are level two, and 15 and 7 are level three.
    The root 3 is level one, 9 and 20 are level two, and 15 and 7 are level three.
    Input:  [3, 9, 20, null, null, 15, 7]
    Output: [[3], [9, 20], [15, 7]]
    Input:  []
    Output: []

    Constraints (assumed)

    • 0 ≤ nodes ≤ 2,000.

    What this question tests

    • BFS on a tree with a queue.
    • Separating levels cleanly using the queue size.
    • Comparing BFS with a DFS that tracks depth.

    Questions to ask first

    1. Left to right within a level? (Yes.)
    2. What should an empty tree return? (An empty list.)
    3. Top-down or bottom-up order? (Top-down; bottom-up is a common variant.)
    4. Any limits on memory? The queue can hold about half the nodes for a full tree.