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 are also counted into the length calculation.

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

Example 1:

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

Example 2:

Input: root = [1,3,null,5,3]
Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).
class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        qs = [(root, 0)]
        width = 0
        
        while len(qs) > 0:
            width = max(width, qs[-1][1] - qs[0][1] + 1)
            next_qs = []#一个queue只存储一个bst层的值
            for q, p in qs:
                if q.left:
                    next_qs.append((q.left, p * 2))
                if q.right:
                    next_qs.append((q.right, p * 2 + 1))
            qs = next_qs
        
        return width
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        if root.right is None and root.left is None:
            return 1
        hw = dict()
        def dfs(root, level, val):
            if root is None:
                return None
            if level in hw:
                hw[level][0] = min(hw[level][0], val)
                hw[level][1] = max(hw[level][1], val)
            else:
                hw[level] = [val,val]
            dfs(root.left,level+1, val*2-1)
            dfs(root.right, level+1, val*2)
        dfs(root,0,1)
        ans = 1
        for v in hw.values():
            ans = max(ans, v[1]-v[0]+1)
        return ans