Address https://leetcode-cn.com/contest/biweekly-contest-12/problems/tree-diameter/
You tree "No to the tree," you measure and return to its "diameter": the number of sides this tree longest simple path.
We use an array of all "sides" of the composition edges
expressed an undirected tree, which edges[i] = [u, v]
represents a node u
and v
two-way between the edges.
The tree nodes have been used {0, 1, ..., edges.length}
to make the tag number, marked on each node is unique.
Example 1
Input: Edges = [[ 0 , . 1 ], [ 0 , 2 ]] Output: 2 Explanation: This tree is the longest path . 1 - 0 - 2 , the number of sides is 2 .
Example 2
Input: Edges = [[ 0 , . 1 ], [ . 1 , 2 ], [ 2 , . 3 ], [ . 1 , . 4 ], [ . 4 , . 5 ]] Output: 4 Explanation: This tree is the longest path . 3 - 2 - . 1 - 4 - . 5 , the number of sides of 4 .
Algorithm 1
seeking maximum distance no tree is divided into two steps to
a point BFS or DFS optionally acquire the point furthest away from the point
2 to the point from the first step or starting again BFS DFS acquired farthest point. Both distance is the maximum distance
C ++ code
1 class Solution { 2 public: 3 pair<int, int> bfs(vector<vector<int>>& e, int start) { 4 vector<int> d(e.size(), -1); 5 6 queue<int> Q; 7 Q.push(start); 8 d[start] = 0; 9 10 pair<int, int> ret; 11 12 while (!Q.empty()) { 13 int x = Q.front(); 14 Q.pop(); 15 ret.first = x; 16 ret.second = d[x]; 17 for (auto& y : e[x]) { 18 if (d[y] == -1) { 19 d[y] = d[x] + 1; 20 Q.push(y); 21 } 22 } 23 } 24 return ret; 25 } 26 27 int treeDiameter(vector<vector<int>>& edges) { 28 int n = edges.size() + 1; 29 vector<vector<int>> e(n, vector<int>()); 30 for (auto& edge: edges) { 31 e[edge[0]].push_back(edge[1]); 32 e[edge[1]].push_back(edge[0]); 33 } 34 35 pair<int, int> p; 36 p = bfs(e, 0); 37 p = bfs(e, p.first); 38 39 return p.second; 40 } 41 };