二叉树中的最大和路径

问题描述 投票:2回答:1

我试图解决这个问题:https://leetcode.com/problems/binary-tree-maximum-path-sum/description/

要找到最大和路径就像找到任意两个节点之间的最大路径一样,该路径可能会也可能不会通过根路径;除了使用最大和路径我们想要跟踪总和而不是路径长度。

因此,我调整了二叉树解决方案的直径以找到最大和路径。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:

    def height(self, root):
        if root==None:
            return 0

        lh = self.height(root.left)
        rh = self.height(root.right)

        return max(root.val+lh, root.val+rh)

    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root==None:
            return 0

        lh = self.height(root.left)
        rh = self.height(root.right)

        ld =  self.maxPathSum(root.left)
        rd =  self.maxPathSum(root.right)

        return max(lh+rh+root.val, root.val+ max(ld , rd))

我的解决方案是在失败前传递40个测试用例。

我坚持试图找出正确的解决方案。我的解决方案适用于查找直径,我只是在返回值中添加了sum。

为什么这不是通用解决方案,因为我显然遍历所有路径并采用适当的最大值返回值。

谢谢你的帮助。

python algorithm recursion data-structures binary-tree
1个回答
2
投票

问题是这一行

return max(lh+rh+root.val, root.val+ max(ld , rd))

它应该是

return max(lh+rh+root.val, max(ld , rd))

请注意,根节点不是ldrd路径的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.