原题链接在这里:https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/
题目:
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:
[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 }