Maximum Width of Binary Tree

Problem Summary

What is Being Asked?

Why This Works

Main Concepts Used

Time & Space Complexity

Code

class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        q = deque([(root, 1)])
        max_width = 0
        while q:
            left_most_index = q[0][1]
            right_most_index = q[-1][1]
            max_width = max(max_width, abs(left_most_index - right_most_index) + 1)
            for _ in range(len(q)):
                node, index = q.popleft()
                if node.left:
                    q.append((node.left, (index * 2)))
                if node.right:
                    q.append((node.right, (index * 2) + 1))
        return max_width

Common Mistakes / Things I Got Stuck On