# LeetCode 1339. Maximum Product of Splitted Binary Tree

2022-09-10 01:30:09  阅读：155  来源： 互联网

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)```

Constraints:

• The number of nodes in the tree is in the range `[2, 5 * 104]`.
• `1 <= Node.val <= 104`

Two round of DFS.

First round to calculate the sum.

Second round to update the res.

After we have the current sum and total sum of the tree. The product is (current sum) * (totoal sum - current sum).

Time Complexity: O(n).

Space: O(logn). stack space.

AC Java:

``` 1 /**
2  * Definition for a binary tree node.
3  * public class TreeNode {
4  *     int val;
5  *     TreeNode left;
6  *     TreeNode right;
7  *     TreeNode() {}
8  *     TreeNode(int val) { this.val = val; }
9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     long res = 0;
18     long sum = 0;
19     long cur;
20     public int maxProduct(TreeNode root) {
21         sum = dfs(root);
22         dfs(root);
23         return (int)(res % (int)(1e9 + 7));
24     }
25
26     private long dfs(TreeNode root){
27         if(root == null){
28             return 0;
29         }
30
31         cur = root.val + dfs(root.left) + dfs(root.right);
32         res = Math.max(res, cur * (sum - cur));
33         return cur;
34     }
35 }```

2. 关于本站的所有留言、评论、转载及引用，纯属内容发起人的个人观点，与本站观点和立场无关；
3. 关于本站的所有言论和文字，纯属内容发起人的个人观点，与本站观点和立场无关；
4. 本站文章均是网友提供，不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属；如您发现该文章侵犯了您的权益，可联系我们第一时间进行删除；
5. 本站为非盈利性的个人网站，所有内容不会用来进行牟利，也不会利用任何形式的广告来间接获益，纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。