01 · Question
Find the level whose next level has the most nodes. If there is no next level, treat prolificness as 0.
02 · Solution
1def mostProlificLevel(root: Optional[TreeNode]) -> int:2 if not root:3 return -14 from collections import deque, defaultdict5 q = deque([(root, 0)])6 level_count = defaultdict(int)7 while q:8 node, depth = q.popleft()9 level_count[depth] += 110 if node.left:11 q.append((node.left, depth + 1))12 if node.right:13 q.append((node.right, depth + 1))14 best_level = 015 best = 016 for level in level_count:17 if level + 1 in level_count and level_count[level + 1] > best:18 best = level_count[level + 1]19 best_level = level20 return best_level