给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]
1
/ \
2 3
输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
输出: 42
题解:
可采用递归思路,对每一个节点,经过该节点的路径最大和为max(root, root+left, root+right, root+left+right),而这可以用一个表达式表示:root+max(left, 0)+max(right, 0),得到的值与记录最大和的变量比较若大则更新。
经过当前节点并与上级节点连接的最大路径和为:max(root, root+left, root+right) (注意与上面相比少了一项),同样可表示为:
root+max(max(left, 0), max(right, 0))
最终结果如下:
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
res = float('-inf')
def getmax(node):
if not node:
return 0
left = max(getmax(node.left), 0)
right = max(getmax(node.right), 0)
nonlocal res
res = max(node.val+left+right, res)
max_ = max(left, right) + node.val
return max_
getmax(root)
return res