8.18练手 腾讯50题 124

本文详细解析了LeetCode第124题“Binary Tree Maximum Path Sum”的两种解法,一种是通过构建图并寻找最大路径,另一种是使用递归方法。展示了如何在二叉树中找到从任意节点到任意节点的最大路径和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode 124. 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 sequence of nodes 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.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

一开始写的方法是,将整个链表树变成图,然后找图的最大有效路径,代码如下:

# 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:
        if(root == None):
            return 0
        elif(root.left == None and root.right == None):
            return root.val
        num = self.countNum(root)
        #create a tree graph
        num = num + 1
        TreeGraph = [0]*num*num
        print(num)
        curPoint1 = 0
        curPoint2 = 1
        stack = []
        stack.append(root)
        TreeGraph[curPoint1*num+curPoint2]=root.val
        TreeGraph[curPoint2*num+curPoint1]=root.val
        while len(stack)!= 0:
            cur = stack.pop()
            curPoint1 = curPoint1 + 1
            if cur.left!= None:
                stack.append(cur.left)
                curPoint2 = curPoint2 +1
                print(curPoint1,curPoint2,cur.left.val)
                TreeGraph[curPoint1*num+curPoint2] = cur.left.val
                TreeGraph[curPoint2*num+curPoint1] = cur.left.val
            if cur.right != None:
                stack.append(cur.right)
                curPoint2 = curPoint2 + 1
                print(curPoint1,curPoint2,cur.right.val)
                TreeGraph[curPoint1*num+curPoint2] = cur.right.val
                TreeGraph[curPoint2*num+curPoint1] = cur.right.val
            
       
        print(TreeGraph)
        #build finish
        for i in range(num):
            for j in range(num):
                if i!=j:
                    for k in range(num):
                        if i!=k and j!=k:
                            if(TreeGraph[i*num+j] < TreeGraph[i*num+k]+TreeGraph[k*num+j] and TreeGraph[i*num+k]!=0 and TreeGraph[k*num+i]!=0):
                                TreeGraph[i*num+j] = TreeGraph[i*num+k]+TreeGraph[k*num+j]
                                print(TreeGraph,i,k,j)
        
        return max(TreeGraph)
        
    def countNum(self, root:TreeNode)->int:
        if(root == None):
            return 0
        return (1 + self.countNum(root.left) + self.countNum(root.right))

 

可以说是很麻烦的方法了,不是很Geek,同时也超过了时间限制。

 

查看了别人的方法,递归真是个好东西。

class Solution:
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        res = float('-inf')
        def maxPath(node):
            nonlocal res 
            if not node:
                return 0
            
            left = max(0, maxPath(node.left))
            right = max(0, maxPath(node.right))
            res = max(res, left + right + node.val)
            return max(left, right) + node.val
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值