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]

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84978154