0
点赞
收藏
分享

微信扫一扫

[算法导论] 1339. 分裂二叉树的最大乘积

MaxWen 2022-02-15 阅读 48

0.题目

分裂一条边,子树结点和 的乘积最大。

分裂一条边,原二叉树会被分为 一个小子树、和原二叉树-小子树的部分。

分裂哪条边,只需要考虑遍历小子树的根结点。再用小子树的sum 与 其他部分和的乘积 更新 res

1. 后序遍历子树值,保存在数组中 o(t) o(max(t,h))=o(t)

用数组保存小子树求和可能的值。

最后用数组更新res。

class Solution(object):
    def maxProduct(self, root):
        treesum = []
        # 结点值求和
        def getsum(root):
            if not root:    return 0
            res = root.val + getsum(root.left) + getsum(root.right)
            treesum.append(res) #treesum保存 子树结点值的和
            return res
举报

相关推荐

0 条评论