LeetCode 1339. Maximum Product of Splitted Binary Tree
2022/9/10 6:24:32
本文主要是介绍LeetCode 1339. Maximum Product of Splitted Binary Tree,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
原题链接在这里:https://leetcode.com/problems/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)
Constraints:
- The number of nodes in the tree is in the range
[2, 5 * 104]
. 1 <= Node.val <= 104
题解:
Two round of DFS.
First round to calculate the sum.
Second round to update the res.
After we have the current sum and total sum of the tree. The product is (current sum) * (totoal sum - current sum).
Time Complexity: O(n).
Space: O(logn). stack space.
AC 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 sum = 0; 19 long cur; 20 public int maxProduct(TreeNode root) { 21 sum = dfs(root); 22 dfs(root); 23 return (int)(res % (int)(1e9 + 7)); 24 } 25 26 private long dfs(TreeNode root){ 27 if(root == null){ 28 return 0; 29 } 30 31 cur = root.val + dfs(root.left) + dfs(root.right); 32 res = Math.max(res, cur * (sum - cur)); 33 return cur; 34 } 35 }
这篇关于LeetCode 1339. Maximum Product of Splitted Binary Tree的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升