方法1:BFS
this is a problem related to BFS. Key point is that:
If the index of a parent node is Ci, accordingly we can define the index of its left child node as 2 * Ci, and the index of its right child node as 2 * Ci + 1.
# 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: TreeNode) -> int:
if root is None:
return 0
queue = [(root, 0)]
res = 0
while queue:
res = max(res, queue[-1][1] - queue[0][1] + 1)
for i in range(len(queue)):
node, index = queue.pop(0)
if node.left:
queue.append((node.left, 2 * index))
if node.right:
queue.append((node.right, 2 * index + 1))
return res