Maximum Product of Splitted Binary Tree

Given the `root` of a binary tree, remove exactly one edge so the tree splits into two subtrees, and make the product of the two subtree sums as large as possible. Return that maximum product modulo $10^9 + 7$. Maximize the product itself first and only then take the remainder.

30:00

Maximum Product of Splitted Binary Tree
medium
Free written solution
Topics
Companies

Given the root of a binary tree, remove exactly one edge so the tree splits into two subtrees, and make the product of the two subtree sums as large as possible.

Return that maximum product modulo 109+710^9 + 7. Maximize the product itself first and only then take the remainder.

Example 1:
Input: {"root":[1,2,3,4,5,6]}
Output: 110
Constraints:
  • The number of nodes in the tree is in the range [2,5×104][2, 5 \times 10^4].

  • 1≤1 \le Node.val ≤104\le 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,2,3,4,5,6]}

Cutting the edge above a node splits off that node's whole subtree. If its sum is s and the tree's total is T, the product is s * (T - s). First collect every subtree sum with one post-order DFS.

T = ?
best = 0
pass 1: subtree sums (0/6)
123456
subtree sum known
cut-off subtree (s)
rest of tree (T - s)
removed edge
best cut
Variables
VariableValue
nodes6
DepthFunction Call
Stack empty
0/14