原题
Given a 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.
For example:
Given the below binary tree,1 / 2 3Return
6
.
解题思路
- 递归求解
- 简化问题,先考虑全是正数的情况下的解法
- 重点:需要两个最大值,一个是当前树的最大路径,即当前节点值加上左右子树的节点值;另一个是当前树向父节点提供的最大路径,这个值应该是根节点的值加上路径最长的子树那边的最大路径,向上层递归函数返回这个值。
- 于是考虑到负值的话即为:需要两个最大值,一个是当前树的最大路径,即当前节点值加上左右子树的路径和(如果左右子树路径和为正的话);另一个是当前树向父节点提供的最大路径,这个值应该是根节点的值加上路径最长的子树那边的最大路径,向上层递归函数返回这个值。
完整代码
# 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 """ if root == None: return 0 self.maxSum = -sys.maxint self._maxPathSum(root) return self.maxSum def _maxPathSum(self, node): """ :type node: TreeNode :rtype: 对于上层根的最大路径和 """ if node == None: return 0 node_max = node.val lPathSum, rPathSum = self._maxPathSum(node.left), self._maxPathSum(node.right) if lPathSum > 0: node_max += lPathSum if rPathSum > 0: node_max += rPathSum # 求此节点当为根节点时的最大路径和 if self.maxSum < node_max: self.maxSum = node_max # 返回对于上层根节点的最大路径和 return max(node.val, node.val + lPathSum, node.val + rPathSum)