Problem Description
Given the root of a binary tree, split the tree into two subtrees by removing exactly one edge such that the product of the sums of the nodes in the resulting subtrees is maximized. Return the maximum possible product of these sums modulo 10^9 + 7.
Key Insights
- We need to maximize the expression: subtree_sum * (total_sum - subtree_sum) for any valid subtree split.
- A two-pass approach is effective: first, compute the total sum of the tree; second, use a DFS to compute the sum for each subtree and consider removing the edge leading to that subtree.
- The use of DFS (post-order traversal) allows us to calculate subtree sums in one go.
- Taking the modulo (10^9 + 7) only at the final step, as the intermediate values may be large.
- Edge removal effectively splits the tree at every possible subtree; the maximum product found during traversal is the answer.
Space and Time Complexity
Time Complexity: O(n) because each node in the tree is visited once during the DFS. Space Complexity: O(h) due to the recursion stack, where h is the height of the tree.
Solution
The solution uses a Depth-First Search (DFS) approach with two passes:
- In the first pass, a DFS is used to calculate the total sum of all nodes in the tree.
- In the second DFS, for each node, the sum of the subtree rooted at that node is computed. For each such node, if you remove the edge from its parent, you effectively split the tree into two parts: one with the current subtree sum and the other with (total sum - current subtree sum). Calculate the product for this split and track the maximum product encountered.
- Return the maximum product modulo 10^9 + 7.
This approach efficiently leverages recursion and a simple arithmetic observation to arrive at the solution.