Binary Tree Maximum Path Sum
错误点:negative也可能是最大值,所以global maxVal初始值为INT_MIN。但是左右传上来的一侧值(left or right)一定要先和0比较再加到local maxVal做比较,因为如果left or right是negative,那么root可以选择不用。
# 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 = -sys.maxint-1
if not root: return 0
self.maxdfs(root)
return self.maxSum
def maxdfs(self, root):
leftMax = 0
if root.left:
leftMax = max(0, self.maxdfs(root.left))
rightMax = 0
if root.right:
rightMax = max(0, self.maxdfs(root.right))
if leftMax + rightMax + root.val>self.maxSum:
self.maxSum = leftMax + rightMax + root.val
return max(leftMax+root.val, rightMax+root.val, root.val)