【发布时间】:2018-08-10 10:12:03
【问题描述】:
我正在尝试解决这个问题: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