4月30天leetcode训练-Day11&&29

本文解析了二叉树的最大直径和最大路径和的算法实现,通过递归方式,巧妙地解决了这两个问题。文章详细介绍了如何利用递归特性,通过比较左右子树的深度或路径和,找到二叉树中最长的路径或最大的路径和。

Day11-Diameter of Binary Tree

问题描述:

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

从二叉树中找到最大的直径(两个节点之间的路径长度).

Example:

Given a binary tree
          1
         / \
        2   3
       / \     
      4   5    
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

解法:

这道题应该用递归求解是第一反应吧,我原先想的是求左右子树的深度然后相加就完事了,但是在写的过程中没有想到用一个全局变量表示最后的结果,如果没有全局变量表示的话遇到不经过root节点的情况就麻烦了,比如说左子树为空的情况下,这时最长路径就不会经过根节点了。所以我们要设置一个全局变量比较每个节点的左右子树的深度之和和当前全局变量的最大值。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        #左子树能到达的最底一层,与右子树能到达的最底一层的和,如果左右子树为空
        def max_dep(root):
            if not root:
                return 0
            left = max_dep(root.left)
            right = max_dep(root.right)
            self.result = max(self.result,left + right)
            return max(left,right) + 1#当前节点的深度
        self.result = 0
        max_dep(root)
        return self.result

如果有大佬看到这篇文章希望能指点一下,这种递归算法的时间复杂度。。。感激不尽啊。

   	  1
     / 
    2   
   /     
  4       

如果是这种情况的话,也是合理的,题中说的是两个节点的距离,而没有限定在两个叶子节点中。。

Day29-Binary Tree Maximum Path Sum

补完第11天的题,看到今天更新的题突然发现这两题好像啊,都是二叉树,都是用递归算法写,代码结构都差不多了。就贴到一起写吧。

问题描述:

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:

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

解法:

我们想求路径的最大和,而且还是个树形结构,应该是用递归做的吧,那递归的特点就是从根节点调用递归函数到叶子节点,然后叶子节点更新状态再返回到根节点。这时我们看第二个例子,先遍历到叶子节点了15了,次时的最大路径就是15吧,就那一个数字嘛,然后网上走,到了20那个节点,这时的路径是不是就是15(左子树最大) + 7(右子树最大) + 20(当前节点) = 42,这时我们还要将这个42和我们设置的最大路径变量进行比较更新这个变量,因为是任意起始节点,所以有可能一个树杈就形成了最大的路径,比如这个例二,我们从20往上走后,到了-10这时这个点左子树最大为9,右子树最大为20 + max(左子树,右子树),因为我们只能选择一条路径,不能重复绕来绕去,然后接下来就跟上面一样更新最大变量就完事了。
还有两个点是我们最大路径变量的初始值应该是负无穷大,因为有可能整个树全是负数,还有一个是我们返回左右子树最大值时我们要将他们的值和0进行比较,因为如果都比0小了,我们肯定不走那条路了。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        self.result = float('-inf') 
        def helper(root):
            if not root:
                return 0
            left = max(helper(root.left),0)
            right = max(helper(root.right),0)
            self.result = max(self.result , left + right + root.val)
            return max(left,right) + root.val
        helper(root)
        return self.result
            

最后贴下我看的解析
吧,要是我解析的没听懂或者认为我说的不对的,可以去看看这个博客,一起讨论一下。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值