1339. Maximum Product of Splitted Binary Tree

Link

Solution

取得所有Node的和 (Total sum)

答案就是所有case: 子樹的和 (subsum) * ( totalsum - subsum)

  long max = 0, total = 0; 
    public int maxProduct(TreeNode root) {
        total = dfs(root);
        dfs(root);
        return (int)(max % ((int)1e9 + 7));
    }
    
    public long dfs(TreeNode node){
        if(node == null) return 0;
        long left = dfs(node.left);
        long right = dfs(node.right);
        long ret = node.val + left + right;
        if(total != 0){
            max = Math.max(max, (total-ret) * ret);
        }
        return ret;
    }

Last updated

Was this helpful?