> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Maximum Width of Binary Tree Python Solution

> Tested Python solution for LeetCode 662 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 662, Medium. Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree. [View on LeetCode](https://leetcode.com/problems/maximum-width-of-binary-tree/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 662   # by problem number
lcpy gen -s maximum_width_of_binary_tree   # by problem name
```

## 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 in the range of a **32-bit** signed integer.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/05/03/width1-tree.jpg)

```
Input: root = [1,3,2,5,3,null,9]
Output: 4
Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).
```

![Example 2](https://assets.leetcode.com/uploads/2022/03/14/maximum-width-of-binary-tree-v3.jpg)

```
Input: root = [1,3,2,5,null,null,9,6,null,7]
Output: 7
Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
```

![Example 3](https://assets.leetcode.com/uploads/2021/05/03/width3-tree.jpg)

```
Input: root = [1,3,2,5]
Output: 2
Explanation: The maximum width exists in the second level with length 2 (3,2).
```

### Constraints

* The number of nodes in the tree is in the range `[1, 3000]`.
* `-100 <= Node.val <= 100`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximum_width_of_binary_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximum_width_of_binary_tree/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque

from leetcode_py import TreeNode


class Solution:
    # Time: O(n)
    # Space: O(w) where w is maximum width
    def width_of_binary_tree(self, root: TreeNode[int] | None) -> int:
        if not root:
            return 0

        max_width = 1
        queue = deque([(root, 0)])

        while queue:
            level_size = len(queue)
            _, first_pos = queue[0]
            last_pos = first_pos

            for _ in range(level_size):
                node, pos = queue.popleft()
                last_pos = pos

                if node.left:
                    queue.append((node.left, 2 * pos))
                if node.right:
                    queue.append((node.right, 2 * pos + 1))

            max_width = max(max_width, last_pos - first_pos + 1)

        return max_width
```

## Complexity

| Time | Space                         |
| ---- | ----------------------------- |
| O(n) | O(w) where w is maximum width |

## Tags

[Grind](/catalog/grind), [NeetCode All](/catalog/neetcode).
