2049. Count Nodes With the Highest Score
Description
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 the number of nodes that have the highest score.
Example 1:
Input: parents = [-1,2,0,2,0] Output: 3 Explanation: - The score of node 0 is: 3 * 1 = 3 - The score of node 1 is: 4 = 4 - The score of node 2 is: 1 * 1 * 2 = 2 - The score of node 3 is: 4 = 4 - The score of node 4 is: 4 = 4 The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.
Example 2:
Input: parents = [-1,2,0] Output: 2 Explanation: - The score of node 0 is: 2 = 2 - The score of node 1 is: 2 = 2 - The score of node 2 is: 1 * 1 = 1 The highest score is 2, and two nodes (node 0 and node 1) have the highest score.
Constraints:
n == parents.length
2 <= n <= 105
parents[0] == -1
0 <= parents[i] <= n - 1
fori != 0
parents
represents a valid binary tree.
Solutions
Solution: Depth-First Search
- Time complexity: O(n)
- Space complexity: O(n)
JavaScript
js
/**
* @param {number[]} parents
* @return {number}
*/
class Node {
left = null;
right = null;
constructor(val) {
this.val = val;
}
}
const countHighestScoreNodes = function (parents) {
const n = parents.length;
const nodes = new Array(n)
.fill('')
.map((_, index) => new Node(index));
const scoreMap = {};
let maxScore = 0;
for (let index = 1; index < n; index++) {
const node = nodes[index];
const parent = nodes[parents[index]];
parent.left ? (parent.right = node) : (parent.left = node);
}
function dfsNodeTree(node = nodes[0]) {
if (!node) return 0;
const left = dfsNodeTree(node.left);
const right = dfsNodeTree(node.right);
const count = left + right + 1;
const restCount = n - count;
const score = (left || 1) * (right || 1) * (restCount || 1);
scoreMap[score] = (scoreMap[score] ?? 0) + 1;
maxScore = Math.max(score, maxScore);
return count;
}
dfsNodeTree();
return scoreMap[maxScore];
};