LeetCode刷题实战124:二叉树中的最大路径和
共 1419字,需浏览 3分钟
·
2020-12-16 21:14
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any node sequence 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.
题意
解题
边界判断
递归找出左右子树最大的gain,小于0就不选。
取以当前节点为根节点的最大值和root为根节点最大值为最大路径和
返回每个节点作为根节点的最大路径作为子树的最大路径。
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
def max_gain(node):
nonlocal max_sum
if not node:return 0
left_max = max(max_gain(node.left), 0)
right_max = max(max_gain(node.right),0)
new_price = node.val + left_max + right_max
max_sum = max(max_sum, new_price)
return node.val + max(left_max, right_max)
max_sum = float('-inf')
max_gain(root)
return max_sum