You're given an undirected tree with n nodes labeled from 0 to n-1. Each node has a specific value, and your goal is to strategically delete edges to split the tree into multiple connected components where all components have the same total value.
Input:
nums: An array wherenums[i]represents the value of nodeiedges: A 2D array whereedges[i] = [a, b]represents an edge between nodesaandb
Goal: Return the maximum number of edges you can delete such that every remaining connected component has the same sum of node values.
Key Insight: If we can split the tree into k components with equal values, then each component must have a total value of total_sum / k, where total_sum is the sum of all node values.
Input & Output
Visualization
Time & Space Complexity
For each divisor of total sum (at most n), we perform DFS traversal of O(n)
Recursion stack for DFS and adjacency list storage
Constraints
- 1 โค nums.length โค 2 ร 104
- 1 โค nums[i] โค 104
- edges.length == nums.length - 1
- edges[i].length == 2
- 0 โค edges[i][0], edges[i][1] < nums.length
- The input represents a valid tree