每日一道算法题--leetcode 124--二叉树中的最大路径和--python

【题目描述】

【源代码】

class Solution(object):
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.res = float('-inf')
        self.dfs(root)
        return self.res
   
    def dfs(self, root):
        if not root:
            return 0
        #print '执行dfs(',root.val,')'
        left = max(0, self.dfs(root.left))
        right = max(0, self.dfs(root.right))
        #print 'self.res',left + root.val + right
        self.res = max(self.res, left + root.val + right)
        #print '返回给上层的是',root.val + max(left, right)
        return root.val + max(left, right)
复制代码

 

猜你喜欢

转载自blog.csdn.net/c710473510/article/details/89378705