662. Maximum Width of Binary Tree
When find result in one of tree level. Can use bfs.
# 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:
dq = deque([[root, 0]])
res = 0
while dq:
lens = len(dq)
l, r = 0 , 0
for i in range(lens):
node, idx = dq.popleft()
if i == 0:
l = idx
if i == lens -1:
r = idx
if node.left:
dq.append([node.left, 2*idx + 1])
if node.right:
dq.append([node.right, 2*idx + 2])
res = max(res, r - l + 1)
return res