int solution(int n, vector<vector<int>> flattree)
requirement :
1. build a tree from flattree.
2. flattree[i] for each valid i contains two elements and represents an edge that connects flattree[i][0] and flattree[i][1].
3. It is guaranteed that given graph is a tree, i.e. it is connected and has no cycles.
4. the tree may has more than one branch.
5.Guaranteed constraints:
flattree.length = n - 1,
flattree[i].length = 2,
0 ≤ flattree[i][j] < n.
6. the return is the max the diameter of the tree. It is the longest path in the two any vertex.
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> adj;
pair<int, int> dfs(int node, int parent) {
pair<int, int> res = {0, node};
for (int child : adj[node]) {
if (child != parent) {
pair<int, int> child_res = dfs(child, node);
res = max(res, {child_res.first + 1, child_res.second});
}
}
return res;
}
int solution(int n, vector<vector<int>> flattree) {
adj = vector<vector<int>>(n);
for (const auto &edge : flattree) {
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
pair<int, int> p = dfs(0, -1);
pair<int, int> q = dfs(p.second, -1);
return q.first;
}