Leetcode—1339. 分裂二叉树的最大乘积【中等】

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
}

运行结果

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

相关推荐
badhope3 小时前
Mobile-Skills:移动端技能可视化的创新实践
开发语言·人工智能·git·智能手机·github
码云数智-园园4 小时前
微服务架构下的分布式事务:在一致性与可用性之间寻找平衡
开发语言
C++ 老炮儿的技术栈4 小时前
volatile使用场景
linux·服务器·c语言·开发语言·c++
hz_zhangrl4 小时前
CCF-GESP 等级考试 2026年3月认证C++一级真题解析
开发语言·c++·gesp·gesp2026年3月·gespc++一级
大阿明4 小时前
Spring Boot(快速上手)
java·spring boot·后端
Liu628885 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
IT猿手5 小时前
基于控制障碍函数的多无人机编队动态避障控制方法研究,MATLAB代码
开发语言·matlab·无人机·openclaw·多无人机动态避障路径规划·无人机编队
AI科技星5 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
sunwenjian8865 小时前
Java进阶——IO 流
java·开发语言·python
参.商.5 小时前
【Day41】143. 重排链表
leetcode·golang