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.
解释:
就是字面意思,让我们在树中找最大路径。
思考:
树有一个很重要的特点,每个子节点一定只有一个父节点,这个特性非常重要,根据这个特性我们可以得出最大路径它一定是有且仅有一个最高点的,因此我们可以设计一个函数,用来计算当前节点的单边最大路径=max(左,右)+val。当我们得到了所有节点的单边最大值之后,同时更新一个所有的最大值即可找到所有路径最大值.根据这种思路通过了Oj,复杂度46%
答案:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.single = 0
self.double = 0
class Solution(object):
def __init__(self):
self.res=0
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res=root.val
self.helper(root)
return self.res
def helper(self,root):
if root==None:
return 0
else :
leftVal = self.helper(root.left)
rightVal = self.helper(root.right)
#这里要考虑到负数的情况
root.single=max(leftVal,rightVal,0)+root.val
root.double=max(leftVal+rightVal,leftVal,rightVal,0)+root.val
self.res=max(self.res,root.double)
return root.single