Maximum Product of Splitted Binary Tree - Problem

Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.

Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.

Note: You need to maximize the answer before taking the mod and not after taking it.

Input & Output

Example 1 — Basic Tree
$ Input: root = [1,2,3,4,5,6]
Output: 110
💡 Note: Remove edge above node 2. Left subtree sum = 2+4+5 = 11, right subtree sum = 1+3+6 = 10. Product = 11 × 10 = 110
Example 2 — Simple Tree
$ Input: root = [1,null,2,3,4,null,null,5,6]
Output: 90
💡 Note: Remove edge above node 3. Left subtree sum = 3+5 = 8, remaining sum = 1+2+4+6 = 13. But removing above node 4 gives: subtree = 4+6 = 10, remaining = 9. Product = 10 × 9 = 90
Example 3 — Single Split
$ Input: root = [2,3,9,10,7,8,6,5,4,11,1]
Output: 1025
💡 Note: Find the optimal cut that maximizes the product of the two resulting subtree sums

Constraints

  • The number of nodes in the tree is in the range [2, 5 × 104]
  • 1 ≤ Node.val ≤ 104

Visualization

Tap to expand
Maximum Product of Splitted Binary TreeOriginal Tree:123456Optimal Split:Left Subtree2 + 4 + 5 = 11Right Subtree1 + 3 + 6 = 10×Product = 11 × 10= 110✂ Cut hereTry all possible cuts to find maximum productAnswer: 110 (mod 10⁹ + 7)
Understanding the Visualization
1
Input Tree
Binary tree with node values [1,2,3,4,5,6]
2
Find Best Cut
Try removing each edge to split into two subtrees
3
Maximum Product
Cut above node 2 gives product 110
Key Takeaway
🎯 Key Insight: Use DFS to efficiently calculate subtree sums and find the optimal cut point
Asked in
Amazon 35 Google 28 Microsoft 22 Facebook 18
52.0K Views
Medium-High 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