Skip to content

Most Prolific Level

01 · Question

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

02 · Solution

Reference solution

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