Maximum Width of Binary Tree - Problem

Given the root of a binary tree, return the maximum width of the given tree.

The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.

It is guaranteed that the answer will be in the range of a 32-bit signed integer.

Input & Output

Example 1 — Standard Tree
$ Input: root = [1,3,2,5,3,null,9]
Output: 4
💡 Note: At level 3, we have nodes 5, 3, and 9. In a complete binary tree representation, positions would be 0, 1, and 3, giving width = 3 - 0 + 1 = 4
Example 2 — Skewed Tree
$ Input: root = [1,3,2,5,null,null,9,6,null,7]
Output: 7
💡 Note: At the deepest level, nodes 6 and 7 span from position 0 to position 6 in the complete tree representation, giving width = 6 - 0 + 1 = 7
Example 3 — Single Node
$ Input: root = [1]
Output: 1
💡 Note: Tree has only root node, so maximum width is 1

Constraints

  • The number of nodes in the tree is in the range [1, 3000]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
Maximum Width of Binary Tree1Level 1: Width = 132Level 2: Width = 2539Level 3: Width = 4 (includes null gaps)Position indices: 5(0), 3(1), null(2), 9(3)Maximum Width = 4🎯 Key Insight: Use BFS with position tracking to calculate width including null gaps
Understanding the Visualization
1
Input Tree
Binary tree with array representation [1,3,2,5,3,null,9]
2
Level Analysis
Calculate width for each level using position indices
3
Maximum Width
Return the largest width found: 4
Key Takeaway
🎯 Key Insight: Assign position indices to nodes using binary tree properties and calculate width as the span between leftmost and rightmost positions at each level
Asked in
Facebook 25 Google 18 Amazon 12 Microsoft 8
87.0K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen