Untitled
class Solution { private long totalSum = 0; private long maxProduct = 0; private static final int MOD = 1_000_000_007; public int maxProduct(TreeNode root) { // Step 1: Calculate the total sum of the tree totalSum = calculateTotalSum(root); // Step 2: Calculate the maximum product by splitting the tree calculateSubtreeSum(root); // Step 3: Return the result modulo MOD return (int) (maxProduct % MOD); } private long calculateTotalSum(TreeNode node) { if (node == null) { return 0; } return node.val + calculateTotalSum(node.left) + calculateTotalSum(node.right); } private long calculateSubtreeSum(TreeNode node) { if (node == null) { return 0; } // Calculate the sum of the current subtree long subtreeSum = node.val + calculateSubtreeSum(node.left) + calculateSubtreeSum(node.right); // Calculate the product of splitting at this subtree long product = subtreeSum * (totalSum - subtreeSum); // Update the maximum product maxProduct = Math.max(maxProduct, product); return subtreeSum; } }
Leave a Comment