1. 程式人生 > >python leetcode 124. Binary Tree Maximum Path Sum

python leetcode 124. Binary Tree Maximum Path Sum

又是一道好題啊。難點在於如何根據題意設計DFS過程。想一想如何求得由這個節點向下的路徑最大值。這個節點的值必然包括,左邊的值是max(0,l),右邊的是max(0,r)。所以設定helper函式是求包括這個節點在內的最大單邊路徑和,不能直接設定為最大雙邊路徑和(這樣會分岔不符合題意)。

class Solution:
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0 
        res=
[-2**31] def helper(root): if not root: return 0 rv,l,r=root.val,0,0 if root.left: l=helper(root.left) if root.right: r=helper(root.right) res[0]=max(res[0],rv+max(0,l)+max(0,r)) return rv+max(l,
r,0) helper(root) return res[0]