-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path1339. Maximum Product of Splitted Binary Tree
49 lines (36 loc) · 1.26 KB
/
1339. Maximum Product of Splitted Binary Tree
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
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
long long totalSum = 0;
long long mod = 1e9+7;
// total sum of tree
void TotalSum(TreeNode* root)
{
if(root==NULL) return;
TotalSum(root->left);
TotalSum(root->right);
totalSum += root->val;
}
long SubtreeSum(TreeNode* root,long long &maxPro)
{
if(root==NULL) return 0;
long l = SubtreeSum(root->left,maxPro);
long r = SubtreeSum(root->right,maxPro);
long curr_sum = l + r + root->val; // curr subtree sum
long curr_Pro = (curr_sum * (totalSum - curr_sum)); // curr product
if(maxPro < curr_Pro)
{
maxPro = curr_Pro;
}
return curr_sum; // for each node return their subtree sum for upcoming nodes pro calculations
}
int maxProduct(TreeNode* root)
{
// First we will calculate the sum of whole tree
// then we will calculate the sum of subtree for each node Individually
// now we will calculate the product -> ( subtree sum for node * (total sum - subtree sum for node) )
TotalSum(root);
long long maxPro = 1;
SubtreeSum(root,maxPro);
return (maxPro % mod);
}
};