Count Nodes With the Highest Score - Problem

Imagine you're a tree surgeon tasked with analyzing a special binary tree structure! ๐ŸŒณ

You have a binary tree rooted at node 0 with n nodes labeled from 0 to n-1. The tree structure is given as a parents array where parents[i] represents the parent of node i. Since node 0 is the root, parents[0] = -1.

Here's the interesting part: each node has a score calculated by a unique method. To find a node's score, imagine removing that node and all edges connected to it. This splits the tree into one or more separate subtrees. The node's score is the product of the sizes of all resulting subtrees.

Your goal: Find how many nodes achieve the maximum possible score.

Example: If removing a node creates subtrees of sizes [2, 3, 1], the score would be 2 ร— 3 ร— 1 = 6.

Input & Output

example_1.py โ€” Basic Tree
$ Input: parents = [-1,2,0,2]
โ€บ Output: 3
๐Ÿ’ก Note: Tree structure: 0 is root with children 2. Node 2 has children 1 and 3. Removing nodes 1, 2, or 3 gives the maximum score of 4, so answer is 3.
example_2.py โ€” Single Node
$ Input: parents = [-1]
โ€บ Output: 1
๐Ÿ’ก Note: Only one node (root). Removing it creates no subtrees, so score is 1. Only 1 node achieves this maximum score.
example_3.py โ€” Linear Tree
$ Input: parents = [-1,0,1,2]
โ€บ Output: 2
๐Ÿ’ก Note: Linear tree: 0->1->2->3. Removing node 1 or 2 gives maximum score by creating more balanced partitions.

Constraints

  • n == parents.length
  • 2 โ‰ค n โ‰ค 105
  • parents[0] == -1
  • 0 โ‰ค parents[i] โ‰ค n - 1 for i != 0
  • parents represents a valid binary tree

Visualization

Tap to expand
Tree Node Score Analysis0Root1234Score CalculationsNode 0 (remove): 1 ร— 3 = 3Components: [1], [2,3,4]Node 1 (remove): 4 = 4Components: [0,2,3,4]Node 2 (remove): 1ร—1ร—2 = 2Components: [3], [4], [0,1]Node 3 (remove): 4 = 4Components: [0,1,2,4]Node 4 (remove): 4 = 4Components: [0,1,2,3]Maximum Score: 4Count: 3 nodes (1, 3, 4)
Understanding the Visualization
1
Build Tree Structure
Convert parent array into adjacency list representation
2
Calculate Subtree Sizes
Use DFS to find size of subtree rooted at each node
3
Compute Node Scores
For each node, score = product of all resulting component sizes
4
Track Maximum
Count how many nodes achieve the highest possible score
Key Takeaway
๐ŸŽฏ Key Insight: When removing a node, the resulting components are its child subtrees plus the remaining upper portion of the tree. Calculate efficiently using pre-computed subtree sizes!
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
32.4K Views
Medium-High Frequency
~25 min Avg. Time
856 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