[leetcode]543.Diameter of Binary Tree(Python)

[leetcode]543.Diameter of Binary Tree

题目描述

Category:Easy 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.
在这里插入图片描述

题目理解

给定一棵二叉树,计算树的周长。树的周长定义为树的子节点间最长的路径。

解题思路

递归

depth函数:遍历二叉树,在每个节点计算左子树和右子树的深度,同时更新ans的值(保证ans的值一直更新为最大值),每次执行返回左子树和右子树中高度更大的值,便于计算二叉树的最长周长。
最后,返回ans的值即为所求的最大周长。
思路借鉴:https://blog.csdn.net/danspace1/article/details/86556411

def diameterOfBinaryTree(self, root: TreeNode) -> int:
    self.ans = 0

    def depth(root):
        if not root:
            return 0
        left = depth(root.left)
        right = depth(root.right)
        self.ans = max(self.ans, left + right)
        return max(left, right) + 1

    depth(root)
    return self.ans

代码分析

Runtime:44ms 66.84%
MemoryUsage:15.1MB 100.00%

Time

2020.3.16 时间好快哦~不知道什么时候才能开学

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值