- Maximum Product of Splitted Binary Tree
class Solution {
public int maxProduct(TreeNode root) {
long ss = getSumRecursively(root);
long max=getMaxProductRecursively(root, ss);
long m=1000000007L;
return (int)(max%m);
}
public long getMaxProductRecursively(TreeNode root ,long ss) {
if(root==null){
return 0L;
}
long ls =getSumRecursively(root.left);
long rs =getSumRecursively(root.right);
long max=((ss-rs)*rs>ls*(ss-ls))?(ss-rs)*rs:ls*(ss-ls);
long lMax=getMaxProductRecursively( root.left, ss);
long rMax=getMaxProductRecursively( root.right, ss);
if(max<lMax)
max=lMax;
if(max<rMax)
max=rMax;
return max;
}
public long getSumRecursively(TreeNode root){
if(root==null)
return 0L;
return getSumRecursively(root.left)+getSumRecursively(root.right)+root.val;
}
}