1.Description
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
2.Example
3.Code
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
maxx = [-999999]
#某一个根节点到某个子节点的最长路径
def maxsum(root):
if root == None:
return 0
else:
l = maxsum(root.left)
r = maxsum(root.right)
result = max(root.val+max(l, r),0)
maxx[0] =max(maxx[0] , root.val+l+r)
return result
maxsum(root)
return maxx[0]
4.Result