Maximum width of binary tree

November 15, 2022

tree

Problem URL: Maximum width of binary tree

We will use BFS to find the maximum width of the tree.

# 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:
        queue = collections.deque([(root,0)])
        res = 0

        while queue:
            res = max(res, queue[-1][1]-queue[0][1]+1)
            for i in range(len(queue)):          
                node, cur = queue.popleft()
                if node.left:
                    queue.append((node.left, 2*cur))
                if node.right:
                    queue.append((node.right, 2*cur+1))

        return res

Time complexity: O(n)
Space complexity: O(n)