一、Problem
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)
Constraints:
Each tree has at most 50000 nodes and at least 2 nodes.
Each node’s value is between [1, 10000].
二、Solution
方法一:求子樹和
- 求一個頂點的子樹和 sub,然後再求非此頂點其他結點的總和不太現實。
- 不如先求整顆樹的總和 tot,然後求出一棵子樹的和 sub,用 tot - sub 就可得到其他結點的總和了。
class Solution {
long tot, max, MOD = (long) 1e9+7;
long dfs1(TreeNode root) {
if (root == null) return 0;
return root.val + dfs1(root.left) + dfs1(root.right);
}
long dfs2(TreeNode root) {
if (root == null) return 0;
long sub = root.val + dfs2(root.left) + dfs2(root.right);
max = Math.max(max, (tot - sub) * sub);
return sub;
}
public int maxProduct(TreeNode root) {
tot = dfs1(root);
dfs2(root);
return (int) (max % MOD);
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,