https://leetcode.com/problems/binary-tree-maximum-path-sum/
递归题目。值得回味。
这里对每个node的path要分为两种,一种是以这个node为起点的path,有三条,root.val, root.val + root.leftpath, root.val + root.rightpath ;第二种就是经过这个node的path,即 root.leftpath + root.val + root.rightpath. 因为node的val可能为负数,所以可能只有root一个node的path最大
一开始我的思路就是比较这四种path递归就行。code如下。但是这样会造成root.leftpath可能选成了p4, 即root.left仅仅是个过路点,那么这个时候对于root而言,比较root.val + root.leftpath或者是 root.leftpath + root.val + root.rightpath都是没有意义的。
class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None: return -1<<31
p1 = root.val
p2 = root.val + self.maxPathSum(root.left)
p3 = root.val + self.maxPathSum(root.right)
p4 = root.val + self.maxPathSum(root.right) + self.maxPathSum(root.left)
return max(p4, max(p1, max(p2, p3)))
所以这里递归应该只返回以root为起点的path,然后在每次递归的时候,把p4那种过路点的path加入到比较中来,再跟新全局的max值。
这里要用一个全局的max值来记录每次的max,因为最终的结果是在递归过程中的值,而不是像以前一样递归结束后的值
正确的AC code如下。这里给了两个maxsum,第一个maxsum 参考http://www.cnblogs.com/zuoyuan/p/3745606.html,这里对lmax和rmax<0的情况进行了剪枝,因为如果他们小于0,就肯定没有直接用root.val的path大。
还提供了自己写的maxsum2的函数,未剪枝,效率比maxsum差了不止一点点!
class Solution(object):
def maxsum(self, root):
if root == None: return 0
sum = root.val
lmax = 0; rmax = 0
if root.left:
lmax = self.maxsum(root.left)
if lmax > 0:
sum += lmax
if root.right:
rmax = self.maxsum(root.right)
if rmax > 0:
sum += rmax
if sum > Solution.max: Solution.max = sum
return max(root.val, max(root.val + lmax, root.val + rmax))
def maxsum2(self, root):
if root == None: return 0
lmax, rmax = 0, 0
if root.left:
lmax = self.maxsum2(root.left)
if root.right:
rmax = self.maxsum2(root.right)
p1 = root.val
p2 = root.val + lmax
p3 = root.val + rmax
res = max(p1, max(p2, p3))
res1 = max(res, root.val + lmax + rmax)
Solution.max = max(res1, Solution.max)
return res
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
Solution.max = -1<<31
if not root: return 0
self.maxsum(root)
return Solution.max