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
思路
这是一道hard题,思路很难想,但代码却特简单。
求树里的最长路径。
之前挺怕这种题的,这次大概了解思路以后写了一个,发现没那么难。
关于树的题目很常会用到递归的。而递归一般是让自己的左右子节点计算。可以想一下,如果把问题放到最下面的叶节点上,能不能轻松地返回一个答案? 而对于头节点,能不能利用左右子树的结果,计算出答案?
一般来说很多问题可能直接return cal(root)了,但这题有一个比较难想到的是用了一个成员变量来记录最大值,而不是直接返回结果。
我们这个递归函数干的事有两件
- 计算以输入的节点作为根节点的路径的最大值,并维护成员变量maxmum
- 从输入的节点开始往下走的路径最大值。这件事其实也是为第一点服务,不过是为了父节点的计算。
解释起来费劲啊。
代码
class Solution:
def __init__(self):
self.maximum = -sys.maxsize
def maxPathSum(self, root: TreeNode) -> int:
if not root:
return root
self.cal(root)
return self.maximum
def cal(self, root):
if not root.left and not root.right:
self.maximum = max(self.maximum, root.val)
return max(0, root.val)
leftmax = rightmax = 0
if root.left:
leftmax = self.cal(root.left)
if root.right:
rightmax = self.cal(root.right)
cur = leftmax + rightmax + root.val
self.maximum = max(self.maximum, cur)
return max(leftmax + root.val, rightmax + root.val, 0)
上面是我一开始的代码,然而写法可以简化。cal函数可以允许null值输入,返回个0就好了,这样可以合并那段终止递归的if语句,并且调用的时候不需要检查输入。
class Solution:
def __init__(self):
self.maximum = -sys.maxsize
def maxPathSum(self, root: TreeNode) -> int:
if not root:
return root
self.cal(root)
return self.maximum
def cal(self, root):
if not root:
return 0
leftmax = self.cal(root.left)
rightmax = self.cal(root.right)
self.maximum = max(self.maximum, leftmax + rightmax + root.val)
return max(leftmax + root.val, rightmax + root.val, 0)