Maximum Width of Binary Tree

Medium Trees & BST Traversals

Maximum Width of Binary Tree is a medium trees & bst problem solved with the traversals pattern. The best approach, optimal (bfs with re-based spots), runs in O(n) time and O(w) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (keep the empty spots) up.

Problem

You are given the root of a binary tree. Return the maximum width over all of its levels.

The width of one level is measured between its leftmost and its rightmost node (the nodes that are not null). Count every spot between them that the level would have if the tree were complete there, including the empty spots, plus the two end nodes themselves. A level with a single node has width 1.

The answer is guaranteed to fit in a signed 32-bit integer.

Examples

Example 1

Input
root = [1, 2, 3, 4, null, null, 5]
Output
4
Why
On the bottom level, 4 is the leftmost node and 5 the rightmost. Between them sit two empty spots (the missing right child of 2 and the missing left child of 3), so the width is 4.

Example 2

Input
root = [1, 2, 3, 4, null, null, 5, 6, null, null, 7]
Output
8
Why
The bottom level holds only 6 and 7, but they hang from the far left and the far right of the tree. A full tree would have 8 spots on that level, and 6 and 7 are the first and the last of them.

Example 3

Input
root = [1, 2, 3, 4, null, null, 5, 6]
Output
4
Why
Level 2 spans from 4 to 5, width 4. The level below holds only 6, width 1. The widest level does not have to be the deepest one.

Constraints

  • The number of nodes is in the range [1, 3000].
  • -100 <= Node.val <= 100
  • The answer fits in a signed 32-bit integer.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (keep the empty spots)O(total width of all levels)O(maximum width)
DFS (first spot per depth)O(n)O(h)
Optimal (BFS with re-based spots)O(n)O(w)

1Brute force (keep the empty spots)

TimeO(total width of all levels)Every spot between the first and last node of a level is stored and looked at, empty or not. Two long branches on the far left and far right make that 2^h spots on level h.
SpaceO(maximum width)Two levels are held at a time, each as long as its width.

Build each level as a list that also holds the empty spots between its nodes, written as null. The next level is the two children of every entry, where an empty spot has two empty children. Cut the nulls off both ends; the length of what is left is the width. This follows the definition directly, but the lists can grow as wide as the tree, which can be 2^31 spots.

  1. Start with the level [root] and best = 0.
  2. While the level is not empty: best = max(best, its length).
  3. Build the next level: for every entry add its left and right child, or two nulls for a null entry.
  4. Drop the nulls at the start and at the end of the next level, and continue with it. Return best.
class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        List<TreeNode> level = new ArrayList<>();
        level.add(root);
        int best = 0;
        while (!level.isEmpty()) {
            best = Math.max(best, level.size());
            List<TreeNode> next = new ArrayList<>();
            for (TreeNode node : level) {
                next.add(node == null ? null : node.left);
                next.add(node == null ? null : node.right);
            }
            int lo = 0, hi = next.size() - 1;
            while (lo <= hi && next.get(lo) == null) lo++;
            while (hi >= lo && next.get(hi) == null) hi--;
            level = new ArrayList<>(next.subList(lo, hi + 1));
        }
        return best;
    }
}

2DFS (first spot per depth)

TimeO(n)Each node is visited once with constant work.
SpaceO(h)The recursion stack and the list of starts both have one entry per depth, and the depth h can be n for a chain.

Number the spots instead of storing them: the root is spot 0 and the children of spot p are spots 2p and 2p + 1. A depth-first search that goes left before right reaches the leftmost node of every depth first, so it records that node's spot as the start of the depth. Every later node at that depth gives a width of its spot minus the start plus 1. To stop the numbers from doubling out of range, each node passes its spot relative to the start of its own depth to its children. All nodes of one depth are numbered from the same base, so the differences stay exact.

  1. dfs(node, depth, pos): if node is null, return.
  2. If depth equals the number of recorded starts, this is the first node at this depth: record pos as the start.
  3. rel = pos - start[depth]; best = max(best, rel + 1).
  4. Recurse into the left child with spot 2 * rel and into the right child with spot 2 * rel + 1.
  5. Start with dfs(root, 0, 0) and return best. rel is below the width, so 2 * rel + 1 fits in a 64-bit integer.
class Solution {
    private List<Long> start = new ArrayList<>();
    private long best = 0;

    public int widthOfBinaryTree(TreeNode root) {
        dfs(root, 0, 0);
        return (int) best;
    }

    private void dfs(TreeNode node, int depth, long pos) {
        if (node == null) return;
        if (depth == start.size()) start.add(pos);   // leftmost node of this depth
        long rel = pos - start.get(depth);           // re-base: the depth starts at 0
        best = Math.max(best, rel + 1);
        dfs(node.left, depth + 1, 2 * rel);
        dfs(node.right, depth + 1, 2 * rel + 1);
    }
}

3Optimal (BFS with re-based spots)

TimeO(n)Each node enters and leaves the queue once.
SpaceO(w)The queue holds at most two levels of real nodes, about w, the largest number of nodes on one level.

Go level by level with a queue that holds each node together with its spot. When a level starts, the spot at the front of the queue is the leftmost spot of that level. Subtract it from every spot of the level as it is taken out, so the level runs from 0 to width - 1, and give the children spots 2p and 2p + 1 from the re-based p. The last node taken out of a level has the re-based spot width - 1. Without the re-basing the spots double on every level and a deep tree overflows any fixed-size integer; with it they stay below 2^32.

  1. Put (root, 0) in the queue; best = 0.
  2. While the queue is not empty: size = its length, base = the spot at its front.
  3. Take out size entries. For each, p = spot - base. Queue (left, 2p) and (right, 2p + 1) for the children that exist. Remember the last p.
  4. best = max(best, last p + 1). Return best.
class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        Queue<TreeNode> nodes = new ArrayDeque<>();
        Queue<Long> spots = new ArrayDeque<>();
        nodes.add(root);
        spots.add(0L);
        int best = 0;
        while (!nodes.isEmpty()) {
            int size = nodes.size();
            long base = spots.peek();              // leftmost spot of this level
            long last = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = nodes.poll();
                long p = spots.poll() - base;      // re-base: the level starts at 0
                last = p;
                if (node.left != null) { nodes.add(node.left); spots.add(2 * p); }
                if (node.right != null) { nodes.add(node.right); spots.add(2 * p + 1); }
            }
            best = Math.max(best, (int) (last + 1));
        }
        return best;
    }
}

Edge cases to test

  • A single node (answer 1)
  • A chain of nodes, all left or all right or zigzagging: every level has one node, so the answer is 1
  • A perfect tree: the bottom level is full, so the answer is the number of leaves
  • Two long branches running down the far left and the far right: the width doubles on every level, up to 2^31 - 1
  • A deep chain that ends in a node with two children: numbering positions from the root without re-basing would need numbers like 2^3000, which overflow even 64-bit integers, while the answer is just 2
  • The widest level is not always the deepest one

Hints

Hint 1

Number the spots on each level as if the tree were complete: the root is spot 0, and a node at spot p has its children at spots 2p and 2p + 1. The width of a level is then last spot minus first spot plus 1.

Hint 2

Visit the tree level by level with a queue that carries each node's spot. The first and the last node of a level give its width.

Hint 3

On a deep tree, the spots double on every level and overflow quickly. Subtract the level's first spot from every spot of that level before computing the children's spots. The numbers then stay below twice the width.

FAQ

What is the best time complexity for Maximum Width of Binary Tree?

Optimal (BFS with re-based spots) runs in O(n) time and O(w) extra space. Each node enters and leaves the queue once.

Which pattern does Maximum Width of Binary Tree use?

It is a trees & bst problem that uses the traversals pattern. Other problems with the same pattern: Binary Tree Level Order Traversal, Binary Tree Zigzag Level Order Traversal, Binary Tree Level Order Traversal II.

Is there a brute force solution for Maximum Width of Binary Tree?

Yes. Brute force (keep the empty spots) takes O(total width of all levels) time and O(maximum width) space. Build each level as a list that also holds the empty spots between its nodes, written as null.

Which edge cases should I test for Maximum Width of Binary Tree?

A single node (answer 1); A chain of nodes, all left or all right or zigzagging: every level has one node, so the answer is 1; A perfect tree: the bottom level is full, so the answer is the number of leaves; Two long branches running down the far left and the far right: the width doubles on every level, up to 2^31 - 1; A deep chain that ends in a node with two children: numbering positions from the root without re-basing would need numbers like 2^3000, which overflow even 64-bit integers, while the answer is just 2; The widest level is not always the deepest one.