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
解法
递归思路:
求某个节点的最长路径和,只需要求左节点的最长路径和left,右节点的最长路径和right,以及当前节点的值val
maxpath = max(val, val+left, val+right, val+left+right)
递归函数返回的时候是一条链,因此返回max(val, val+left, val+right)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def solve(self, root):
if root:
left = self.solve(root.left)
right = self.solve(root.right)
val = root.val
ret = max(val, val+left, val+right)
self.ans = max(self.ans, ret, val+left+right)
return ret
return 0
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans = -(1<<30)
self.solve(root)
return self.ans