Leetcode Diameter of Binary Tree python 计算二叉树中两点间的最长距离(直径)

Leetcode 543题 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.


题目大意: 计算一个二叉树的直径,直径即为二叉树中两点间的最长距离。
说到二叉树,就离不开递归的迭代。
如何知道一棵树的深度? 一个数的深度=左右两颗子树深度+1
如何知道一棵树的最大宽度? 最大宽度=max(所有左右子树高度的和)

自己定义一个getdepth函数:遍历二叉树,在每个节点计算左子树和右子树的深度,同时更新self.diameter的值(保证self.diameter的值一直更新为最大值),每次执行返回左子树和右子树中高度更大的值,便于计算二叉树的最长周长。
最后,返回ans的值即为所求的最大周长。


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

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

同样看到一个,思路一样,但是把getdepth函数写到大函数里了,一开始很迷,后来想通了就觉得很简单。

2020/04/09
疫情中的英国,加油!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值