Approach

I find that any node (except the root), can be split into a differnt subtree, and the remaining nodes are in another subtree. Therefore, all we have to do is to calculate the sum of the subtree, and the overall sum for all nodes, and try to calculate the maximum product.

Code

class Solution {
public:
    const int mod = 1'000'000'007;
    
    int maxProduct(TreeNode* root) {
        vector<long long> nodeSum;
        long long sum = traverse(root, nodeSum);
        nodeSum.pop_back();
        long long maxP = LONG_MIN;
        for(const auto& s: nodeSum) {
            long long curP = (sum - s) * s;
            maxP = max(maxP, curP);
        }
        return maxP % mod;
    }

    long long traverse(TreeNode* root, vector<long long>& nodeSum) {
        long long sum = 0;
        if(root->left) sum += traverse(root->left, nodeSum);
        if(root->right) sum += traverse(root->right, nodeSum);
        sum += root->val;
        nodeSum.push_back(sum);
        return sum;
    }
};