Given a binary tree root
. Split the binary tree into two subtrees by removing 1 edge such that the product of the sums of the subtrees are maximized.
Since the answer may be too large, return it modulo 10^9 + 7.
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)
Example 3:
Input: root = [2,3,9,10,7,8,6,5,4,11,1] Output: 1025
Example 4:
Input: root = [1,1] Output: 1
Constraints:
- Each tree has at most
50000
nodes and at least2
nodes. - Each node's value is between
[1, 10000]
题目链接:https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/
题目大意:给一棵树,将其分成两部分,求两部分和的积的最大值
题目分析:思路很清楚,求得每个子树和,另一部分子树和用总和减即可,无脑做法是两次dfs,一次求分别以每个节点为根的子树和,第二次算最大值,不知道为啥非要取个模。算一下可知最终答案范围不会超过long
85ms,时间击败5%
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private final long MOD = 1000000007;
private Map<TreeNode, Long> mp = new HashMap<>();
private long ans = 0;
private long dfs(TreeNode root) {
if (root == null) {
return 0;
}
long sum = root.val;
sum += dfs(root.left);
sum += dfs(root.right);
mp.put(root, sum);
return sum;
}
private void solve(TreeNode root, long sum) {
if (root == null) {
return;
}
ans = Math.max(ans, mp.get(root) * (sum - mp.get(root)));
solve(root.left, sum);
solve(root.right, sum);
}
public int maxProduct(TreeNode root) {
dfs(root);
solve(root, mp.get(root));
return (int) (ans % MOD);
}
}
其实刚提交就发现,这个map是多余的,第一次dfs时return的值就对应每个子树和,因此只需要先求出总和,通过dfs函数即可直接算出最优值
6ms,时间击败99.21%
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private final long MOD = 1000000007;
private long ans = 0, sum = 0;
private void calSum(TreeNode root) {
if (root == null) {
return;
}
sum += root.val;
calSum(root.left);
calSum(root.right);
}
private long dfs(TreeNode root) {
if (root == null) {
return 0;
}
long cur = root.val;
cur += dfs(root.left);
cur += dfs(root.right);
long product = cur * (sum - cur);
if (product > ans) {
ans = product;
}
return cur;
}
public int maxProduct(TreeNode root) {
calSum(root);
dfs(root);
return (int) (ans % MOD);
}
}