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
疫情中的英国,加油!