(Leetcode) 二叉树中的最大路径和 - Python实现

题目:二叉树中的最大路径和
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

-----------------------------------------------------------------------------------------------

解法1#:创建递归函数,实现子节点到父节点回溯的方式来计算最大值

注意:最长的路径肯定是属于“从一端的最左侧到这端的最右侧” 这个完整链条的一部分。

class Solution(object):
    def __init__(self):
        self.result = float('-inf')

    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        self.getMax(root)
        return self.result

    def getMax(self, root):
        """辅助函数"""

        # 如果当前节点为空就表示包含当前节点的最大路径为0
        if root == None:
            return 0

        # 递归的计算当前节点的左子树和右子树能提供的最大路径和。如果为负,就置为0(相当于从头开始)
        left = max(0, self.getMax(root.left))
        right = max(0, self.getMax(root.right))

        # 注意:最长的路径肯定是属于从一端的最左侧到这端的最右侧的一部分
        # 每计算一次左右子树的最大值,就更新当前的result
        self.result = max(self.result, left+right+root.val)

        # 回溯到父节点,最大路径就只能包含左右两个子树中的一个
        return max(left, right) + root.val

解法2#:解法1的变体

class Solution(object):

    def maxPathSum(self, root):
        self.curr_max = float('-inf')

        def getMax(root):
            if root == None:
                return 0
            left = max(0,getMax(root.left))
            right = max(0,getMax(root.right))
            self.curr_max = max(self.curr_max , left + right + root.val)
            return max(left,right)+root.val
        getMax(root)

        return self.curr_max

 

参考:

https://blog.csdn.net/ggdhs/article/details/92377456

https://blog.csdn.net/qq_28327765/article/details/86490717

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值