LeetCode124:Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

LeetCode:链接

maxSum用于记录最大路径和,当level为0时返回它。maxPathSum(root)函数返回的是经过root的路径最大和, 可以只是root, 也可以是左子树某一部分+root或者root+右子树某一部分。这个函数是可以返回0的, 也就是说currRoot, currRoot+左子树, currRoot+右子树的值都小于等于0, 对max path sum没有贡献, 之后就不再考虑了。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.maxSum = float("-inf")
        self.dfs(root)
        return self.maxSum
        
    def dfs(self, root):
        if not root:
            return 0
        vleft = self.dfs(root.left)
        vright = self.dfs(root.right)
        self.maxSum = max(self.maxSum, vleft + vright + root.val)
        return max(root.val + vleft, root.val + vright, 0)

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/85857426