[LeetCode] 1339. Maximum Product of Splitted Binary Tree

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

Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.

Note that you need to maximize the answer before taking the mod and not after taking it.

Example 1:

Input: root = [1,2,3,4,5,6]
Output: 110
Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)

Example 2:

Input: root = [1,null,2,3,4,null,null,5,6]
Output: 90
Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)

Example 3:

Input: root = [2,3,9,10,7,8,6,5,4,11,1]
Output: 1025

Example 4:

Input: root = [1,1]
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [2, 5 * 104].
  • 1 <= Node.val <= 104

分裂二叉树的最大乘积。

给你一棵二叉树,它的根为 root 。请你删除 1 条边,使二叉树分裂成两棵子树,且它们子树和的乘积尽可能大。

由于答案可能会很大,请你将结果对 10^9 + 7 取模后再返回。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-splitted-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是后序遍历。这道题请你把一棵树分成两部分,使得两部分的 node.val 的乘积最大,那么我们势必是要求得整棵树里所有的 node.val 的和的,这里我们记为 sum。其次,当我们试图将某条边删除的时候,树会被一分为二,比如例子一里被分割之后形成的 2,4,5 那棵子树,求这个子树的 node.val 的和,是需要通过后序遍历的方式完成的。所以我们需要遍历整棵树两次,第一次求得整棵树里所有的 node.val 的和;第二次我们做后序遍历,对于以当前某个 node 为根节点形成的子树,我们尝试把他切割出来,用这棵子树的节点值的和 x (sum - 这棵子树的节点值的和) 即是题目所求的子树和的乘积,取最大值即可。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     long res = 0;
18     long total = 0;
19     int MOD = (int) Math.pow(10, 9) + 7;
20 
21     public int maxProduct(TreeNode root) {
22         total = dfs(root);
23         dfs(root);
24         return (int) (res % MOD);
25     }
26 
27     private int dfs(TreeNode root) {
28         if (root == null) {
29             return 0;
30         }
31         int sum = dfs(root.left) + dfs(root.right) + root.val;
32         res = Math.max(res, (total - sum) * sum);
33         return sum;
34     }
35 }

 

相关题目

1339. Maximum Product of Splitted Binary Tree

2049. Count Nodes With the Highest Score

LeetCode 题目总结

posted @ 2021-08-20 11:01  CNoodle  阅读(199)  评论(0编辑  收藏  举报