Most Prolific Level

Find the level whose next level has the most nodes. If there is no next level, treat prolificness as 0.

1def mostProlificLevel(root: Optional[TreeNode]) -> int:
2 if not root:
3 return -1
4 from collections import deque, defaultdict
5 q = deque([(root, 0)])
6 level_count = defaultdict(int)
7 while q:
8 node, depth = q.popleft()
9 level_count[depth] += 1
10 if node.left:
11 q.append((node.left, depth + 1))
12 if node.right:
13 q.append((node.right, depth + 1))
14 best_level = 0
15 best = 0
16 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 = level
20 return best_level
1
0
2
1
3
2
4
3
5
4
levelCount={ 0, 1, 2 }
Step 1 / 3
Step 1:
Level-order traversal to count nodes at each depth.
Focus: select @ [0]