Binary Tree Level Order Traversal

Pattern: Level order BFS

medium

Breadth-first search with a queue, one level per round: read the queue size, take exactly that many nodes, and add their children for the next round.

The problem

Return the node values level by level, each level from left to right. [3, 9, 20, null, null, 15, 7] gives [[3], [9, 20], [15, 7]]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • Which structure visits nodes in order of distance from the root?
  • How do you know where one level ends?
  • What goes into the queue after a node is taken?

Hints

    Brute force, and why it fails

    Depth-first with a depth parameter, appending to levels[depth]: also O(n).

    The key insight

    A queue takes nodes in order of depth, and the size at the start of a round marks the level boundary.

    Dry run

    queue3

    root = [3, 9, 20, null, null, 15, 7]. The queue starts with 3: one node on level 0.

    Step 1 of 4

    The plan

    queue = [root]
    while queue:
        size = len(queue); level = []
        repeat size times: n = pop front; level += n; push n's children
        record level
    

    Complexity

    Time
    O(n)
    Space
    O(w)

    Each node enters the queue once; the queue holds at most one level and part of the next.

    Edge cases

    • Empty tree: [].
    • A chain: one value per level.
    • A full tree: the last level holds about half the nodes.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> out = new ArrayList<>();
            Queue<TreeNode> q = new ArrayDeque<>();
            if (root != null) q.add(root);
            while (!q.isEmpty()) {
                int size = q.size();                // exactly the nodes of this level are in the queue
                List<Integer> level = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    TreeNode node = q.poll();
                    level.add(node.val);
                    if (node.left != null) q.add(node.left);
                    if (node.right != null) q.add(node.right);
                }
                out.add(level);
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> out;
            queue<TreeNode*> q;
            if (root != NULL) q.push(root);
            while (!q.empty()) {
                int size = static_cast<int>(q.size());   // exactly the nodes of this level are in the queue
                vector<int> level;
                for (int i = 0; i < size; i++) {
                    TreeNode* node = q.front();
                    q.pop();
                    level.push_back(node->val);
                    if (node->left != NULL) q.push(node->left);
                    if (node->right != NULL) q.push(node->right);
                }
                out.push_back(level);
            }
            return out;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def levelOrder(self, root) -> list[list[int]]:
            out, q = [], deque([root] if root else [])
            while q:
                level = []
                for _ in range(len(q)):             # exactly the nodes of this level are in the queue
                    node = q.popleft()
                    level.append(node.val)
                    if node.left:
                        q.append(node.left)
                    if node.right:
                        q.append(node.right)
                out.append(level)
            return out

    Common mistakes

    • Using the queue's size inside the loop while children are being added.
    • Forgetting to start a new list per level.

    Similar problems