(C++) 2049. Count Nodes With the Highest Score
\n\nclass Solution {\npublic:\n    int countHighestScoreNodes(vector<int>& parents) {\n        int n = parents.size(); \n        vector<vector<int>> tree(n); \n
\n```\nclass Solution {\npublic:\n    int countHighestScoreNodes(vector<int>& parents) {\n        int n = parents.size(); \n        vector<vector<int>> tree(n); \n        for (int i = 0; i < n; ++i) \n            if (parents[i] >= 0) tree[parents[i]].push_back(i); \n        \n        map<long, int> freq; \n        \n        function<int(int)> fn = [&](int x) {\n            int left = 0, right = 0; \n            if (tree[x].size()) left = fn(tree[x][0]); \n            if (tree[x].size() > 1) right = fn(tree[x][1]); \n            long score = 1; \n            if (left) score *= left; \n            if (right) score *= right; \n            if (n - 1 - left - right) score *= n - 1 - left - right; \n            ++freq[score]; \n            return 1 + left + right; \n        };\n        \n        fn(0); \n        return freq.rbegin()->second; \n    }\n};\n```\n\nAlternative implementation\n```\nclass Solution {\npublic:\n    int countHighestScoreNodes(vector<int>& parents) {\n        int n = parents.size(); \n        vector<vector<int>> tree(n); \n        for (int i = 0; i < n; ++i) \n            if (parents[i] >= 0) tree[parents[i]].push_back(i); \n        \n        map<long, int> freq; \n        \n        function<int(int)> fn = [&](int x) {\n            long count = 1, score = 1; \n            for (auto& xx : tree[x]) {\n                int cc = fn(xx); \n                count += cc; \n                score *= cc; \n            }\n            score *= max(1l, n - count); \n            ++freq[score]; \n            return count; \n        };\n        \n        fn(0); \n        return freq.rbegin()->second; \n    }\n};\n```
['C']