[LeetCode]1339. Maximum Product of Splitted Binary Tree

二叉树左右子树之积

Posted by JinFei on August 19, 2021

题目描述

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.

Example1:

二叉树分裂一刀 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)

Example2:

二叉树分裂一刀 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 * 10^4].
  • 1 <= Node.val <= 10^4

解题思路

  • 总共分为三步,第一步先利用递归求得树的全节点之和
  • 遍历到当前节点时,比当前最大的乘积进行相比
  • 求得最大乘积
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    long res = 0;
    long total = 0;
public:
    long rec(TreeNode* root){
        if(root == nullptr){
            return 0;
        }
        int subtree = rec(root -> left) + rec(root -> right) + root -> val;
        res = max(res, (total - subtree) * subtree);
        return subtree;
    }
    int maxProduct(TreeNode* root) {
        total = rec(root); // 这里忽略了22句,只是利用了同一个函数 
        rec(root);
        return res % int(pow(10, 9) + 7);
    }
};