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
好了,今天的文章就到这里。