Tensorum
LeetCode 662 · BFS / Level Order

Maximum Width of Binary Tree

LeetCode 662 · Medium · solution, intuition & step-by-step walkthrough

Heap indices per level, normalised by the level's first index.

MediumTreeDepth-First SearchBreadth-First SearchBinary Tree
84 msruntime · beats 10%
54.2 MBmemory · beats 100%
1approach
6accepted runs · last 8 Jul 2024

This is how I solved Maximum Width of Binary Tree (LeetCode 662), a medium problem from the BFS / Level Order pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Number nodes like a heap: children of index i are 2i+1 and 2i+2. A level's width is last index − first index + 1. To stop the numbers from exploding on deep trees, subtract the level's minimum index before computing children.

Approach

  1. 1

    BFS with (node, index) pairs.

  2. 2

    For each level, note the first and last indices.

  3. 3

    Push children with 2·index+1 / +2 minus the level's minimum.

  4. 4

    Track last − first + 1.

How I solved it

BFS with heap indicesPythonO(n) time
class Solution:
    def widthOfBinaryTree(self, root):
        mx = float("-inf")
        queue = [[root, 0]]
        fast = 0
        last = 0
        while queue:
            size = len(queue)
            minIndex = queue[0][1]
            mx = max(size, mx)
            for i in range(size):
                node, index = queue.pop(0)
                if i == 0:
                    fast = index
                if i == size - 1:
                    last = index
                if node.left:
                    queue.append([node.left, (2 * index + 1) - minIndex])
                if node.right:
                    queue.append([node.right, (2 * index + 2) - minIndex])
            mx = max(mx, last - fast + 1)
        return mx
Loading the step-through…

Maximum Width of Binary Tree — FAQ

What is the intuition behind Maximum Width of Binary Tree?

Number nodes like a heap: children of index i are 2i+1 and 2i+2. A level's width is last index − first index + 1. To stop the numbers from exploding on deep trees, subtract the level's minimum index before computing children.

How do you solve Maximum Width of Binary Tree (LeetCode 662)?

1. BFS with (node, index) pairs. 2. For each level, note the first and last indices. 3. Push children with 2·index+1 / +2 minus the level's minimum. 4. Track last − first + 1.

What is the time and space complexity of Maximum Width of Binary Tree?

Time: O(n). Space: O(n). (Accepted approach: BFS with heap indices.)

What are common mistakes in Maximum Width of Binary Tree?

Without normalising, indices overflow in languages with fixed-width ints.