2025每日刷题(234)
Leetcode---1339. 分裂二叉树的最大乘积

dfs实现代码
go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxProduct(root *TreeNode) int {
var sum func(root *TreeNode) int
sum = func(root *TreeNode) int {
if(root == nil) {
return 0
}
return root.Val + sum(root.Left) + sum(root.Right)
}
s := sum(root)
const mod = 1e9 + 7
var ans int
var dfs func(root *TreeNode) int
dfs = func(root *TreeNode) int {
if(root == nil) {
return 0
}
t := root.Val + dfs(root.Left) + dfs(root.Right)
if(t < s) {
ans = max(ans, t * (s - t))
}
return t
}
dfs(root)
ans %= mod
return ans
}
运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!