其他分享
首页 > 其他分享> > ​LeetCode刷题实战124:二叉树中的最大路径和

​LeetCode刷题实战124:二叉树中的最大路径和

作者:互联网

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个号后续每天带大家做一道算法题,题目就从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.

题意

给定一个非空二叉树,返回其最大路径和。本题中,路径被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。样例watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

解题

思路总结:

 

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



好了,今天的文章就到这里。

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

标签:node,max,sum,路径,LeetCode,124,二叉树,节点,gain
来源: https://blog.51cto.com/u_13294304/2983161