A · Grandmaster · 12 min

Tree Diameter

The longest simple path in a tree. Two BFS/DFS: from any node to a farthest node u, then from u to a farthest node v. uv is a diameter.

A tree is a connected acyclic undirected graph: n nodes, n-1 edges, unique path between any pair. The diameter is the maximum number of edges (or the maximum weighted length) on any simple path.

CSES Tree Diameter. The two-sweep proof: let u be farthest from an arbitrary root. u is an endpoint of some diameter. Then the farthest from u is the other endpoint.

Constraints: n ≤ 2·10⁵ so you get two linear DFS, not all-pairs. Floyd is O(n³) and does not exist.

Two DFS, unweightedjs
function farthest(start, adj) {
  const n = adj.length;
  const dist = Array(n).fill(-1);
  const stack = [[start, 0]];
  dist[start] = 0;
  let best = start;
  while (stack.length) {
    const [u, d] = stack.pop();
    if (d > dist[best]) best = u;
    for (const v of adj[u]) {
      if (dist[v] === -1) {
        dist[v] = d + 1;
        stack.push([v, d + 1]);
      }
    }
  }
  return { node: best, dist };
}

function treeDiameter(n, edges) {
  const adj = Array.from({ length: n }, () => []);
  for (const [u, v] of edges) {
    adj[u].push(v);
    adj[v].push(u);
  }
  const u = farthest(0, adj).node;
  const { dist } = farthest(u, adj);
  return Math.max(...dist);
}

TRACE

Path 0-1-2 with a leaf 3 on 1: edges (0,1),(1,2),(1,3).

DFS from 0

farthest is 2 (or 3), distance 2.

u = 2

1 / 3

CHECK

Why is one DFS from node 0 not enough?

CHECK

CSES Tree Distances I asks the farthest node from *every* node. After you have a diameter uv, what is the answer at x?

Checks 0/2

Next lesson