1339. 分裂二叉树的最大乘积

给你一棵二叉树,它的根为 root 。请你删除 1 条边,使二叉树分裂成两棵子树,且它们子树和的乘积尽可能大。

由于答案可能会很大,请你将结果对 10^9 + 7 取模后再返回。

链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxProduct = function(root) {
let sum = 0
function count(node) {
if (node == null) return
sum += node.val
count(node.left)
count(node.right)
}
count(root)
let best = 0
function findMax(node) {
if (node === null) return 0
const cur = findMax(node.left) + findMax(node.right) + node.val
if (Math.abs(cur * 2 - sum) < Math.abs(best * 2 - sum)) {
best = cur
}
return cur
}
findMax(root)

return best * (sum - best) % 1000000007
};