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: 8
💡 Note: At the deepest level, nodes 6 and 7 are at positions 4 and 11 in the complete tree representation, giving width = 11 - 4 + 1 = 8
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 Tree INPUT Binary Tree Structure 1 3 2 5 3 null 9 L0 L1 L2 Input Array: [1, 3, 2, 5, 3, null, 9] Find max width across levels Width = 4 ALGORITHM (BFS) 1 Use Position Index Assign index: left=2*i right=2*i+1 2 BFS Level Traversal Queue: (node, index) pairs Process level by level 3 Calculate Width Width = lastIdx - firstIdx + 1 Track max width seen 4 Process Each Level L0: idx[0] -- Width=1 L1: idx[0,1] -- Width=2 L2: idx[0,1,3] -- Width=4 Level 2 Queue State: (5,0) (3,1) (9,3) Width = 3-0+1 = 4 Time: O(n) | Space: O(n) n = number of nodes RESULT Maximum Width Found 1 3 2 5 3 9 Width = 4 Output: 4 OK - Max Width = 4 L0:1, L1:2, L2:4 Key Insight: Use position indices (like a complete binary tree) to calculate width. For node at index i: left child = 2*i, right child = 2*i+1. Width = (rightmost index) - (leftmost index) + 1. This counts null nodes between endpoints without storing them. BFS processes level by level efficiently. TutorialsPoint - Maximum Width of Binary Tree | BFS Approach
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