Maximum Width of Binary Tree LeetCode solution in Python
1# Runtime: 46 ms (Top 93.81%) | Memory: 14.7 MB (Top 75.82%)2# Definition for a binary tree node.3# class TreeNode:4# def __init__(self, val=0, left=None, right=None):5# self.val = val6# self.left = left7# self.right = right8class Solution:9def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:10q = deque([(root, 0)])11res = 01213while q:14res = max(res, q[-1][1] - q[0][1] + 1)15for _ in range(len(q)):16curr, pos = q.popleft()1718if curr.left:19q.append((curr.left, pos * 2))20if curr.right:21q.append((curr.right, pos * 2 + 1))2223return res