4
// 1 - For each node, you need to find the sizes of the subtrees rooted in5
// each of its children.7
// 2 - How to determine the number of nodes in the rest of the tree?8
// Can you subtract the size of the subtree rooted at the node from the total9
// number of nodes of the tree?11
// 3 - Use these values to compute the score of the node. Track the maximum12
// score, and how many nodes achieve such score.14
// calculating size of each subtree by standing at every node '0' to 'n-1'15
int dfs(int src, vector<vector<int>> &g, vector<int> &size) {16
int ans = 1; // for curent node17
for (auto child : g[src]) {18
ans += dfs(child, g, size);20
return size[src] = ans;23
// This code can also be work for generalized tree not only for Binary tree24
int countHighestScoreNodes(vector<int> &parents) {25
int n = parents.size();26
vector<int> size(n, 0); // size[i] indicates size of subtree(rooted at i node) + 127
vector<vector<int>> g(n); // storing left and right child of a node28
for (int i = 1; i < n; i++) {29
g[parents[i]].push_back(i); // 'There is no parent for 0th node'32
dfs(0, g, size); // calculating size of each subtree(rooted at ith node)34
long long int maxCount = 0; // To avoid overflow because perform product35
// below you should take "long long int"36
long long int maxScore = 0;37
for (int i = 0; i < n; i++) // Nodes from '0' to 'n-1'39
// calculate score of each node after removal their 'edge' or 'node41
long long int product = 1;42
product = max(product,43
(long long int)(n - size[i])); // calculating leftover nodes44
// excluding child nodes46
product = product * size[x];49
if (product > maxScore) {52
} else if (product == maxScore) {53
maxCount++; // store count of nodes which have maximum score equal to