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 that you need to maximize the answer before taking the mod and not after taking it.
Example 1:
Input: root = [1,2,3,4,5,6] Output: 110
Explanation:
Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)
Example 2:
Input: root = [1,null,2,3,4,null,null,5,6] Output: 90
Explanation:
Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)
Example 3:
Input: root = [2,3,9,10,7,8,6,5,4,11,1] Output: 1025
Example 4:
Input: root = [1,1] Output: 1
Constraints:
- The number of nodes in the tree is in the range [2, 5 * 104].
- 1 <= Node.val <= 104
这本质是一道数学题:
- x + y = k
- x * y = x * (k-x) = kx - x2
- 当x = k/2的时候, kx - x2的值最大, 别问我怎么推的,凭直觉, 然后左右取值试的,真要推倒的话估计是用微积分,但是当年学的东西早还给老师了,只能这样凑活了。
- tree的和是sum, subtree的和越接近sum/2, 这时切除subtree, 两边的乘积最大
代码实现(Rust):
impl Solution {
fn calc_sum(root: &Option<Rc<RefCell<TreeNode>>>, sums: &mut Vec<i32>) -> i32 {
if let Some(r) = root {
let left = Solution::calc_sum(&r.borrow().left, sums);
let right = Solution::calc_sum(&r.borrow().right, sums);
let total = r.borrow().val + left + right;
sums.push(total);
return total;
}
return 0;
}
pub fn max_product(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut sums = Vec::new();
Solution::calc_sum(&root, &mut sums);
let total = *sums.last().unwrap();
let mut diff = total;
let mut half = 0;
for i in 0..sums.len()-1 {
if (total - sums[i] * 2).abs() < diff {
diff = (total - sums[i] * 2).abs();
half = sums[i];
}
}
(((total - half) as i64 * half as i64) % 1000000007 as i64) as i32
}
}
|