二叉树中的最大和路径

时间:2018-03-02 08:04:54

标签: python algorithm recursion data-structures binary-tree

我正在尝试解决这个问题: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个测试用例。

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

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

问题在于这一行

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

应该是

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

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