Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1339. Maximum Product of Splitted Binary Tree

Rain Hu

1339. Maximum Product of Splitted Binary Tree


一、題目

Given the root of a binary tree, split the bianry tree into two subtrees by removing one edge such that the product of the sums of the subtreesis maximized.
Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 10^9 + 7.
Note that you need to maximize the answer before taking the mod and not after taking it.

Example 1:
sample1

Example 2: sample2

Constraints:


二、分析

三、解題

1. DFS

#define ll long long int
#define MOD 1000000007
int maxProduct(TreeNode* root) {
    vector<ll> vec;
    int total = dfs(root, vec); // 遍歷樹,並算出整棵樹的和
    ll res = 0;
    for (ll& x : vec) {
        res = max(res, x * (total-x));  // 截斷邊的兩側樹的和分別為 x 與 total - x
    }
    return res % MOD;
}
int dfs(TreeNode* root, vector<ll> vec) {
    if (!root) return 0;
    int left = dfs(root->left, vec);
    int right = dfs(root->right, vec);
    vec.push_back(root->val + left + right);    // 將子樹的總和記到 vector 中
    return vec.back();                          // 返回子樹的總和,讓父節點可以使用
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 124. Binary Tree Maximum Path Sum
Next
[LeetCode] 1026. Maximum Difference Between Node and Ancestor