DSA Graphs

Tree Diameter

Two BFS passes — first from any node finds a diameter endpoint; second BFS from there measures the diameter.

Medium
Time O(V) Space O(V)
LeetCode
5 min read
tree bfs graph

Problem#

Given an undirected tree as an edge list, return its diameter — the number of edges on the longest path between any two nodes.

Examples#

  • edges = [[0,1],[0,2]]2
  • edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]4

Constraints#

  • 0 <= edges.length < 10^4. Underlying graph is a tree.

Approach#

The classic two-BFS trick. From any node, BFS finds the farthest node u — guaranteed to be on a diameter. BFS from u to find the farthest node v; the distance is the diameter.

Solution#

Tree Diameter
class Solution {
public:
int treeDiameter(vector<vector<int>>& edges) {
int n = edges.size() + 1;
if (n == 1) return 0;
vector<vector<int>> adj(n);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
auto bfs = [&](int src) {
vector<int> dist(n, -1);
queue<int> q;
q.push(src);
dist[src] = 0;
int far = src;
while (!q.empty()) {
int u = q.front(); q.pop();
if (dist[u] > dist[far]) far = u;
for (int v : adj[u]) {
if (dist[v] == -1) { dist[v] = dist[u] + 1; q.push(v); }
}
}
return make_pair(far, dist[far]);
};
auto [u, d0] = bfs(0);
(void)d0;
auto [v, d] = bfs(u);
(void)v;
return d;
}
};

Editorial#

The two-BFS property: in any tree, starting from an arbitrary node and walking to the farthest reachable node always lands on a diameter endpoint. A second BFS from there finds the other end and the diameter length. The proof is a swap argument on optimal paths.

Complexity#

  • Time: O(V).
  • Space: O(V).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.