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 thenumber of nodes that have the highest score.
Input: parents =[-1,2,0,2,0]Output: 3Explanation:
- The score of node 0is:3*1=3- The score of node 1is:4=4- The score of node 2is:1*1*2=2- The score of node 3is:4=4- The score of node 4is:4=4The highest score is4, and three nodes(node 1, node 3, and node 4) have the highest score.
Input: parents =[-1,2,0]Output: 2Explanation:
- The score of node 0is:2=2- The score of node 1is:2=2- The score of node 2is:1*1=1The highest score is2, and two nodes(node 0 and node 1) have the highest score.
To compute the score for each node, we need to know the size of each subtree. We can use DFS to calculate the size of each subtree, and then for each node, calculate the product of the sizes of the resulting subtrees if that node is removed.
classSolution {
funcountHighestScoreNodes(parents: IntArray): Int {
val n = parents.size
val g = Array(n) { mutableListOf<Int>() }
for (i in1 until n) g[parents[i]].add(i)
val sz = IntArray(n)
fundfs(u: Int): Int {
sz[u] = 1for (v in g[u]) sz[u] += dfs(v)
return sz[u]
}
dfs(0)
var mx = 0L; var cnt = 0for (i in0 until n) {
var score = 1Lfor (v in g[i]) score *= sz[v].toLong()
if (i !=0) score *= (n - sz[i]).toLong()
when {
score > mx -> { mx = score; cnt = 1 }
score == mx -> cnt++ }
}
return cnt
}
}
classSolution:
defcountHighestScoreNodes(self, parents: list[int]) -> int:
n = len(parents)
g = [[] for _ in range(n)]
for i in range(1, n):
g[parents[i]].append(i)
sz = [1] * n
defdfs(u):
for v in g[u]:
dfs(v)
sz[u] += sz[v]
dfs(0)
mx, cnt =0, 0for i in range(n):
score =1for v in g[i]:
score *= sz[v]
if i:
score *= n - sz[i]
if score > mx:
mx, cnt = score, 1elif score == mx:
cnt +=1return cnt