Problem
Given an undirected tree, return its diameter: the number of edges in a longest path in that tree.
The tree is given as an array of edges
where edges[i] = [u, v]
is a bidirectional edge between nodes u
and v
. Each node has labels in the set {0, 1, ..., edges.length}
.
Example 1:
1 | Input: edges = [[0,1],[0,2]] |
Example 2:
1 | Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]] |
Constraints:
0 <= edges.length < 10^4
edges[i][0] != edges[i][1]
0 <= edges[i][j] <= edges.length
- The given edges form an undirected tree.
Analysis
题目以边的形式给出一幅图,要求找到这幅图的最长的路径长度。题目只要返回长度,不需要把路径打印出来。假设我们最长的路径起点是a
,终点是b
,如果我们知道了a
或者b
中的其中一个,只用做一次BFS就能找到最长的长度。问题就转化为我们怎么找到最长路径的其中一个顶点。我们只需要任意找一个顶点,然后找到最长的路径,那个终点必定是最长路径的其中一个顶点,详细的证明请看https://stackoverflow.com/questions/20010472/proof-of-correctness-algorithm-for-diameter-of-a-tree-in-graph-theory。
Solution
无。
Code
1 | class Solution { |
Summary
这道题目的难点就是如何找到最长路径的一个起点,具体的证明可以去stack overflow看,这里就算是一个总结了。coding上没有难度,就是两个一样的BFS。这道题目的分享到这里,感谢你的支持!