SDE & MLE Prep

662. Maximum Width of Binary Tree

Problem

The width of a level is the number of positions between its leftmost and rightmost non-null nodes, counting the null positions in between as if the tree were complete. Return the maximum width over all levels.

Example: [1,3,2,5,3,null,9] → 4; [1,3,2,5,null,null,9,6,null,7] → 7

Constraints: up to 3000 nodes; the answer fits in 32 bits.

Give nodes heap indices (left = 2i, right = 2i+1). Width of a level = last index − first index + 1. Re-base indices per level to avoid huge numbers.

Complexity: O(n).

class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        best, q = 0, [(root, 0)]
        while q:
            base = q[0][1]
            best = max(best, q[-1][1] - base + 1)
            nxt = []
            for node, i in q:
                i -= base
                if node.left:
                    nxt.append((node.left, 2 * i))
                if node.right:
                    nxt.append((node.right, 2 * i + 1))
            q = nxt
        return best