算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 二叉树中的最大路径和,我们先来看题面:
https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/
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
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。
上期推文: