<p>Given the <code>root</code> 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.</p>

<p>Return <em>the maximum product of the sums of the two subtrees</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p><strong>Note</strong> that you need to maximize the answer before taking the mod and not after taking it.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/01/21/sample_1_1699.png" style="width: 500px; height: 167px;" />
<pre>
<strong>Input:</strong> root = [1,2,3,4,5,6]
<strong>Output:</strong> 110
<strong>Explanation:</strong> Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/01/21/sample_2_1699.png" style="width: 500px; height: 211px;" />
<pre>
<strong>Input:</strong> root = [1,null,2,3,4,null,null,5,6]
<strong>Output:</strong> 90
<strong>Explanation:</strong> Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[2, 5 * 10<sup>4</sup>]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    long long q = 0;
    
    long long findmax(map<TreeNode*, long long>& m, TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        
        long long leftSum = m[root->left];  // Safe access as NULL returns 0
        long long rightSum = m[root->right];
        
        // Max product by splitting at current node
        long long currentMax = max((q - leftSum) * leftSum, (q - rightSum) * rightSum);
        
        // Recursively find max product in left and right subtrees
        long long leftMax = findmax(m, root->left);
        long long rightMax = findmax(m, root->right);
        
        return max(currentMax, max(leftMax, rightMax));
    }

    long long solve(map<TreeNode*, long long>& m, TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        
        // Check and avoid recomputation if already present
        if (m.find(root) != m.end()) {
            return m[root];
        }
        
        m[root] = root->val + solve(m, root->left) + solve(m, root->right);
        return m[root];
    }
    
    int maxProduct(TreeNode* root) {
        map<TreeNode*, long long> m;
        q = solve(m, root);  // Find total sum and fill the map with subtree sums
        long long result = findmax(m, root);  // Find the maximum product
        return result % 1000000007;  // Apply modulo
    }
};

103445