LeetCode 1339. Maximum Product of Splitted Binary Tree
原题链接
中等
作者:
haaai
,
2021-03-26 03:43:03
,
所有人可见
,
阅读 654
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
typedef long long LL;
const int mod = 1e9 + 7;
class Solution {
public:
LL sum, ans = 0;
LL getSum(TreeNode* node){
if (!node) return 0;
return getSum(node->left) + getSum(node->right) + node->val;
}
LL dfs(TreeNode* node){
if (!node) return 0;
LL sum_d = dfs(node->left) + dfs(node->right) + node->val;
ans = max(ans, sum_d * (sum - sum_d));
return sum_d;
}
int maxProduct(TreeNode* root) {
sum = getSum(root);
dfs(root);
return ans % mod;
}
};