蠡口124. Binary Tree Maximum Path Sum

This question is to get a start, I was thinking recursion, ideas are as follows:

  left=maxPathSum(root.left)

  right=maxPathSum(root.right)

  But how the value of the left and right sides of the recursive link it? If you can find the root path through each left to right and then, talk about the results of a comparison of recursive maximum value can be obtained.

Based on the above ideas, we can define a function pathSum, this function is also seeking path and, but this path must include the root node, and this path can only include a maximum of about one child node in the path. Why can contain only one left right and where it? Because if both contain left, can also contain right, then left the path might hooked left.right from left.left, not through the root. In this way we can find the children left, after a root, to the value of the right of children of this path. As shown below:

We can find the maximum side edge recursive, but pay attention to the results to be included in Left -Root- Right value of such a path, this value is actually max (pathSum ( Left ), 0, pathSum ( Right ), pathSum ( Left ) + pathSum ( Right )). code show as below:

class Solution(object):
    ans=-2**31
    def maxSum(self,root):
        if root==None: return(0)
        left=self.maxSum(root.left)
        right=self.maxSum(root.right)
        self.ans=max(self.ans,max(left,right,0,left+right)+root.val)
        return(max(left,right,0)+root.val)
    
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root==None: return(-2**31)
        self.ans=root.val
        self.maxSum(root)
        return(self.ans)

 

Guess you like

Origin www.cnblogs.com/Leisgo/p/11717554.html