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

Leetcode 124. 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

Answer:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import sys
class Solution(object):
    def maxPathSumOnCurrent(self,node):
        if node==None:
            return 0
        left=node.left
        right=node.right
        
        leftp=max(self.maxPathSumOnCurrent(left),0)
        rightp=max(self.maxPathSumOnCurrent(right),0)
        
        
        self.max=max(self.max,leftp+rightp+node.val)
        return max(leftp,rightp)+node.val
        
            
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.max=-sys.maxsize -1
        self.maxPathSumOnCurrent(root)
        return self.max