#662

Maximum Width of Binary Tree

Medium
TreeDepth-First SearchBreadth-First SearchBinary TreeBreadth-First SearchLevel Order Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a level-order traversal with indices to calculate the width efficiently. By treating the indices as positions in a complete binary tree, we can compute the width without needing to traverse all nodes at each level.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a queue to perform a level-order traversal of the tree, storing each node along with its index.
  2. 2Step 2: For each level, calculate the width using the first and last indices of the non-null nodes.
  3. 3Step 3: Update the maximum width found during the traversal.
solution.py18 lines
1# Full working Python code
2from collections import deque
3
4def widthOfBinaryTree(root):
5    if not root:
6        return 0
7    max_width = 0
8    queue = deque([(root, 0)])
9    while queue:
10        level_length = len(queue)
11        _, first_index = queue[0]
12        for _ in range(level_length):
13            node, index = queue.popleft()
14            if node:
15                queue.append((node.left, 2 * index))
16                queue.append((node.right, 2 * index + 1))
17        max_width = max(max_width, index - first_index + 1)
18    return max_width

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the queue storing nodes at each level.

  • 1The width of a level can be calculated using indices in a complete binary tree format.
  • 2Using a queue allows for efficient level-order traversal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.