Problem Description
Given a binary tree represented by a parents array where each element indicates the parent of that node (with node 0 as the root), remove a node (and its connected edges) to partition the tree into a forest of non-empty subtrees. The score of a node is defined as the product of the sizes of each resulting subtree. The task is to determine how many nodes achieve the highest possible score.
Key Insights
- Use Depth-First Search (DFS) to compute the size of each subtree.
- When a node is removed, its children form separate subtrees. Also, the "rest of the tree" (nodes not in the removed node's subtree) forms an additional subtree.
- The node's score is computed as the product of the sizes of all its resulting subtrees.
- During DFS, update and track the maximum score encountered and count nodes that achieve this score.
Space and Time Complexity
Time Complexity: O(n), since we traverse every node exactly once via DFS.
Space Complexity: O(n), required for storing the tree structure (adjacency list) and the recursion stack in the worst case.
Solution
We first build an adjacency list from the parents array. Then, using DFS starting from the root (node 0), we compute the subtree size for every node. During the DFS, for each node, we calculate its score by multiplying the size of each child's subtree and the size of the "remaining" tree (n - current subtree size, if non-zero). We constantly update the maximum score and count how many nodes have that maximum score. This one-pass DFS ensures optimal performance for large inputs.