★★★★★★★★力扣刷题(python)50天——第三十天:二叉树的最大路径和★★★★★★★★

力扣刷题(python)50天——第三十天:二叉树的最大路径和

题目描述

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

   1
  / \
 2   3

输出: 6
示例 2:

输入: [-10,9,20,null,null,15,7]

-10
/
9 20
/
15 7

输出: 42

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法

由于之前有一个求最大深度的题,因此很容易想到用递归的方法来做这道题。

解答

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    trueval=float('-inf')
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.val=root.val
        self.flag=0
        flag=0
        if root.left:
            self.findleft(root.left,flag)
        self.val+=self.flag
        self.flag=0
        if root.right:
            self.findright(root.right,flag)
        self.val+=self.flag
        self.trueval=max(self.val,self.trueval)
        return self.trueval
            
    def findleft(self,root,flag):
        self.maxPathSum(root)
        flag+=root.val
        if flag>self.flag:
            self.flag=flag
        if root.left:
            self.findleft(root.left,flag)
        if root.right:
            self.findright(root.right,flag)
            
    def findright(self,root,flag):
        self.maxPathSum(root)
        flag+=root.val
        if flag>self.flag:
            self.flag=flag
        if root.left:
            self.findleft(root.left,flag)
        if root.right:
            self.findright(root.right,flag)

想法很好,可惜超时了,总结原因,是因为在找子root的maxPathSum时,重复计算了很多数据
而且看了很多答案这样的思路确实有点难改,因为我没有回溯值,只有对变量的全局修改。
可见https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/solution/er-cha-shu-de-zui-da-lu-jing-he-by-leetcode/把我的问题描述的很好。

参考答案:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        def max_gain(node):
            nonlocal max_sum
            if not node:
                return 0

            # max sum on the left and right sub-trees of node
            left_gain = max(max_gain(node.left), 0)
            right_gain = max(max_gain(node.right), 0)
            
            # the price to start a new path where `node` is a highest node
            price_newpath = node.val + left_gain + right_gain
            
            # update max_sum if it's better to start a new path
            max_sum = max(max_sum, price_newpath)
        
            # for recursion :
            # return the max gain if continue the same path
            return node.val + max(left_gain, right_gain)
   
        max_sum = float('-inf')
        max_gain(root)
        return max_sum

思路的区别在于,我在写该代码的时候是按照以根节点为必过的点来写算法,然后对每个节点执行相同的代码递归,这样就造成了巨大的重复计算。而答案中,对所有的点进行一次遍历,因为答案有回溯值而我没有,所以很难去改。思路差别还是比较大。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值