Count Nodes With the Highest Score Problem
Description
LeetCode Problem 2049.
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.
Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees.
Return the number of nodes that have the highest score.
Example 1:

Input: parents = [-1,2,0,2,0]
Output: 3
Explanation:
- The score of node 0 is: 3 * 1 = 3
- The score of node 1 is: 4 = 4
- The score of node 2 is: 1 * 1 * 2 = 2
- The score of node 3 is: 4 = 4
- The score of node 4 is: 4 = 4
The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.
Example 2:

Input: parents = [-1,2,0]
Output: 2
Explanation:
- The score of node 0 is: 2 = 2
- The score of node 1 is: 2 = 2
- The score of node 2 is: 1 * 1 = 1
The highest score is 2, and two nodes (node 0 and node 1) have the highest score.
Constraints:
n == parents.length2 <= n <= 10^5parents[0] == -10 <= parents[i] <= n - 1fori != 0parentsrepresents a valid binary tree.
Solution
Approach: DFS
Build the children list of every node from parents. Removing node i splits the tree into its children's subtrees plus the rest of the tree (everything outside the subtree of i). The score of i is the product of the sizes of these parts, skipping the "rest" part when it is empty (i is the root).
A DFS returns the subtree size of each node. At node i, start with cnt = 1 and score = 1; for every child multiply score by the child's size and add it to cnt. If n - cnt > 0, multiply score by n - cnt as well. Keep the maximum score seen and how many nodes reach it.
Complexity: time O(n), space O(n).
class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
def dfs(i: int, fa: int):
cnt = score = 1
for j in g[i]:
if j != fa:
t = dfs(j, i)
score *= t
cnt += t
if n - cnt:
score *= n - cnt
nonlocal ans, mx
if mx < score:
mx = score
ans = 1
elif mx == score:
ans += 1
return cnt
n = len(parents)
g = [[] for _ in range(n)]
for i in range(1, n):
g[parents[i]].append(i)
ans = mx = 0
dfs(0, -1)
return ans