题目:
给你一棵根节点为 0 的 二叉树 ,它总共有 n 个节点,节点编号为 0 到 n - 1 。同时给你一个下标从 0 开始的整数数组 parents 表示这棵树,其中 parents[i] 是节点 i 的父节点。由于节点 0 是根,所以 parents[0] == -1 。
一个子树的 大小 为这个子树内节点的数目。每个节点都有一个与之关联的 分数 。求出某个节点分数的方法是,将这个节点和与它相连的边全部 删除 ,剩余部分是若干个 非空 子树,这个节点的 分数 为所有这些子树 大小的乘积 。
请你返回有 最高得分 节点的 数目 。
解答:
class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
n=len(parents)
#children[i]:记录节点i的孩子节点
children=[[] for _ in range(n)]
for child,parent in enumerate(parents):
if parent!=-1:
children[parent].append(child)
#maxscore:记录最大分数
#cnt:记录最大分数出现的次数
maxScore, cnt = 0, 0
#dfs(node):计算以node为根节点的子树大小,同时统计最大分数及其出现的次数
def dfs(node):
nonlocal maxScore, cnt
score = 1
size = n - 1
#遍历该节点的孩子节点
for ch in children[node]:
sz = dfs(ch)
score *= sz
size -= sz
#如果node不是根结点,则还需乘以 父节点除去node分支之后的分支大小(即size)
if node != 0:
score *= size
if score == maxScore:
cnt += 1
#重置最大分数及其个数
elif score > maxScore:
maxScore, cnt = score, 1
return n - size
dfs(0)
return cnt