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
Count Nodes With Highest Score INPUT Binary Tree Structure 0 1 2 3 4 parents array: -1 0 0 1 1 i=0 i=1 i=2 i=3 i=4 n = 5 nodes ALGORITHM STEPS 1 Build Tree Create children list from parents array 2 DFS for Subtree Size Calculate size of each subtree recursively 3 Calculate Scores score = product of remaining subtree sizes 4 Find Max Count Count nodes with highest score Score Calculation: Node 0: 2*1 = 2 Node 1: 1*1*2 = 2 Node 2: 4 = 4 (max) Node 3: 4 = 4 (max) Node 4: 4 = 4 (max) Max = 4, Count = 3 FINAL RESULT Nodes with Max Score (4) 0 score=2 1 score=2 2 score=4 3 score=4 4 score=4 Output: 3 Key Insight: When removing a node, the tree splits into: (1) its left subtree, (2) its right subtree, and (3) remaining nodes (n - subtree_size). The score is the product of non-zero parts. Leaf nodes get high scores because they only remove 1 node, leaving n-1 = 4 nodes. TutorialsPoint - Count Nodes With the Highest Score | DFS with Subtree Size Calculation
Asked in
Microsoft 35 Amazon 28 Google 22
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen