-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1339.cpp
36 lines (36 loc) · 1.06 KB
/
1339.cpp
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
35
36
/**
* 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) {}
* };
*/
class Solution {
public:
long long sum = 0;
long long maxVal = 0;
long long mod = 1e9 + 7;
void dfs(TreeNode* node) {
if (!node) return;
sum += node->val;
dfs(node->left);
dfs(node->right);
}
long long dfsWithMultiply(TreeNode* node) {
if (!node) return 0;
long long sumLeft = dfsWithMultiply(node->left);
long long sumRight = dfsWithMultiply(node->right);
maxVal = max(maxVal, sumLeft * (sum - sumLeft));
maxVal = max(maxVal, sumRight * (sum - sumRight));
return sumLeft + sumRight + node->val;
}
int maxProduct(TreeNode* root) {
dfs(root);
dfsWithMultiply(root);
return maxVal % mod;
}
};