leetcode 543: 二叉树的直径

leetcode 543:二叉树的直径


这是一道面试高频题,经常要手撕代码(牛客网看了一下大佬们对手撕代码的解释,xswl,哈哈哈我喜欢椒盐味的)。
虽然难度是 简单,但是对于初级者或粗心的人有坑🕳,我就是😔,我本质是个小菜鸡啊~

题目描述

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
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.

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

解法

这次就写写思路及踩坑、优化过程,因为这道题也没太多解法。然后是看了一个题解,跟他的心路历程简直一样的hhh,所以在这里引用一下~

首先,掉坑里。
最大直径,就是左子树最大高度+右子树最大高度啊!
然后马上码代码,测试用例正确,然后点提交,解答错误。
🙂

然后,是修改后。

代码如下:

class Solution
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if not root:
            return 0
        def maxDepth(root):
            if not root:
                return 0
            return 1+max(maxDepth(root.left),maxDepth(root.right))
        depth =  maxDepth(root.right)+maxDepth(root.left)
        right = self.diameterOfBinaryTree(root.right)
        left = self.diameterOfBinaryTree(root.left)
        
        return max(depth,right,left)

运行结果:
第一次提交成功
哇靠!这个耗时,我不能再快了,真的…但是胜在思路清晰,我如此安慰自己道…

最后,是优化后。
没有使用全局变量,参考题解 再初始化函数里添加了一个变量存储最大直径。
在递归中直接对比,减少重复计算。

class Solution:
    def __init__(self):
        self.maxdepth = 0
        
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if not root:
            return 0

        def maxDepth(root):
            global maxdepth
            if not root:
                return 0
            left = maxDepth(root.left)
            right = maxDepth(root.right)
            self.maxdepth = max(self.maxdepth, right+left)
            return 1+max(left, right)
        maxDepth(root)
        return self.maxdepth

运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值