[LeetCode] 124. Binary Tree Maximum Path Sum

题:https://leetcode.com/problems/binary-tree-maximum-path-sum/description/

题目

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

思路

该类问题往往都需要往动态规划上面靠,写出状态转移方程。
在这个问题中,最重要的是 求解的量,不是状态转移方程所需要的结果。它只是结果的一部分。

code

python

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

class Solution:
    def getPathSum(self,root):
        if root == None:
            return 0
        left = max(0,self.getPathSum(root.left))
        right = max(0,self.getPathSum(root.right))
        nodeSum = left+right+root.val
        if nodeSum > self.maxSum:
            self.maxSum = nodeSum
        return max(left,right)+root.val

    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        self.maxSum = root.val
        self.getPathSum(root)
        return self.maxSum

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/80961522