2049. 统计最高分的节点数目
给你一棵根节点为 0 的 二叉树 ,它总共有 n 个节点,节点编号为 0 到 n - 1 。同时给你一个下标从 0 开始的整数数组 parents 表示这棵树,其中 parents[i] 是节点 i 的父节点。由于节点 0 是根,所以 parents[0] == -1 。
一个子树的 大小 为这个子树内节点的数目。每个节点都有一个与之关联的 分数 。求出某个节点分数的方法是,将这个节点和与它相连的边全部 删除 ,剩余部分是若干个 非空 子树,这个节点的 分数 为所有这些子树 大小的乘积 。
请你返回有 最高得分 节点的 数目 。
示例 1:
输入:parents = [-1,2,0,2,0]
输出:3
解释:
- 节点 0 的分数为:3 * 1 = 3
- 节点 1 的分数为:4 = 4
- 节点 2 的分数为:1 * 1 * 2 = 2
- 节点 3 的分数为:4 = 4
- 节点 4 的分数为:4 = 4
最高得分为 4 ,有三个节点得分为 4 (分别是节点 1,3 和 4 )。
示例 2:
输入:parents = [-1,2,0]
输出:2
解释:
- 节点 0 的分数为:2 = 2
- 节点 1 的分数为:2 = 2
- 节点 2 的分数为:1 * 1 = 1
最高分数为 2 ,有两个节点分数为 2 (分别为节点 0 和 1 )。
提示:
- n == parents.length
- 2 <= n <= 1 0 5 10^5 105
- parents[0] == -1
- 对于 i != 0 ,有 0 <= parents[i] <= n - 1
- parents 表示一棵二叉树。
解题思路
- 先创建节点类,用来保存二叉树节点之间的关系以及每个节点下属节点的数量
- 递归查找每个节点的后代节点的数量,保存在每个节点中
- 每次删除某个节点,计算分数的公式为:左子树的节点个数 * 右子树的节点个数 * (总节点数-当前子树节点个数)。遍历所有节点统计最高得分 节点的 数目 。
代码
class Node{
public:
Node *left,*right;
int children;
};
class Solution {
public:
int countHighestScoreNodes(vector<int>& parents) {
map<int,Node*> m;
for (int i = 0; i < parents.size(); ++i) {
m[i]=new Node();
}
for (int i = 1; i < parents.size(); ++i) {
Node *p=m[parents[i]],*cur=m[i];
if (p->left!= nullptr)
p->right=cur;
else p->left=cur;
}
this->total=parents.size();
count(m[0]);
dfs(m[0]);
return maxn;
}
long long maxx=0;
int maxn=0,total;
int count(Node *root){
if (root== nullptr) return 0;
int l=count(root->left),r=count(root->right);
return root->children=(1+l+r);
}
void dfs(Node *root){
if (root== nullptr) return ;
dfs(root->left);
dfs(root->right);
long long num=(long long)(root->left== nullptr?1:root->left->children)*(long long)(root->right== nullptr?1:root->right->children)*(long long)max(1,total-root->children);
if (num>maxx)
{
maxx=num;
maxn=1;
}else if (num==maxx){
maxn++;
}
}
};