Count Nodes With the Highest Score - Problem
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 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.
Input & Output
Example 1 — Basic Tree
$
Input:
parents = [-1,0,0,1,1]
›
Output:
3
💡 Note:
Tree: 0 has children [1,2], node 1 has children [3,4]. Removing node 1 gives score 2×1×1=2. Removing nodes 3,4,2 each give score 4×1=4. Three nodes have the highest score 4.
Example 2 — Single Node
$
Input:
parents = [-1]
›
Output:
1
💡 Note:
Only one node exists. Removing it leaves no subtrees, so score is 1 (by definition). One node has the highest score.
Example 3 — Linear Tree
$
Input:
parents = [-1,0,1]
›
Output:
2
💡 Note:
Linear tree 0-1-2. Removing node 1 gives score 1×1=1. Removing nodes 0 or 2 gives score 2×1=2. Two nodes have the highest score 2.
Constraints
- 2 ≤ parents.length ≤ 105
- parents[0] == -1
- 0 ≤ parents[i] ≤ n - 1 for i != 0
- parents represents a valid tree
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree represented by parents array
2
Node Removal
Remove a node and calculate resulting subtree sizes
3
Calculate Score
Multiply all subtree sizes to get node's score
Key Takeaway
🎯 Key Insight: Use DFS to precompute subtree sizes once, then calculate each removal score in O(1) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code