learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Algorithm Selection

Select an algorithm and generate steps to begin visualization

Tree Diameter and Center

Two searches find the longest path in a tree

Finds the longest path in a tree with two BFS passes and the center in its middle, then confirms the center by peeling leaves

Time: O(n)
Space: O(n)
Use Case: Network latency, minimum height trees, placing a facility on a tree, coding interviews
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Tree Diameter and Center

The diameter of a tree is the length of its longest path, the largest distance between two vertices. Its center is the vertex, or the two adjacent vertices, whose farthest vertex is as close as possible, and that distance is the radius. Camille Jordan proved in 1869 that the center of a tree is always one vertex or two adjacent ones, and it sits in the middle of every longest path. In a general graph the diameter needs a search from every vertex, but in a tree two are enough.

How it works

The first BFS starts anywhere and finds the farthest vertex u. That vertex is always an end of some longest path: if it were not, the path to it could be extended past a longest path, a contradiction. The second BFS starts at u, and its farthest vertex v is the other end, so the distance from u to v is the diameter and the BFS parents give the path. The center is the middle vertex of that path, or the two middle vertices when its length is odd. As a check, leaf peeling removes all leaves round after round until one or two vertices remain, and those are exactly the center. Everything takes O(n). Edges count as length one, weights are ignored. The visualizer shows each BFS distance, draws the longest path in green, marks the round in which each leaf was peeled and colours the center orange.

Applications

In a tree-shaped network the diameter is the worst-case delay between two nodes, and the center is the best place for a server, a hub or a facility that everyone must reach. "Minimum Height Trees" asks for the roots that make a tree as shallow as possible, which are the center, and the two-BFS trick is a classic interview question. On weighted trees with non-negative weights the same two searches work with DFS distances. In graphs with cycles, two searches only give a lower bound on the diameter.

Pseudocode

Two BFS passes for the diameter, and leaf peeling as an independent check of the center.

TreeDiameter(T, s):
    dist = BFS(T, s), u = vertex with the largest dist
    dist, parent = BFS(T, u), v = vertex with the largest dist
    diameter = dist[v]
    path = v, parent[v], parent[parent[v]], ..., u
    center = middle vertex of path (two if diameter is odd)

LeafPeeling(T):                    // the check
    leaves = vertices of degree 1
    while more than 2 vertices remain:
        remove all leaves, lowering their neighbours' degrees
        leaves = neighbours that now have degree 1
    return the 1 or 2 vertices left   // the center

Everything rests on one fact: in a tree, the vertex farthest from any start is an end of some longest path. Its proof uses the unique path between two vertices of a tree, which is why the trick fails on graphs with cycles.

Worked example, step by step

The eleven-vertex tree on this page, with the first BFS from G.

Example graph: Edges A–B, A–C, B–D, B–E, C–F, C–G, D–H, E–I, F–J and J–K. The deepest branch under B ends in H, and the deepest under C ends in K.

  1. BFS from G. G is just a start. The farthest vertex from it is H, 5 edges away along G, C, A, B, D, H. I is just as far, and the first in alphabetical order is kept.
  2. BFS from H. From H the farthest vertex is K, 7 edges away along H, D, B, A, C, F, J, K. So the diameter is 7.
  3. The center. The path has odd length 7, so the center is its two middle vertices, A and C, and the radius is 4.
  4. Peeling round 1. The leaves G, H, I and K are removed.
  5. Rounds 2 and 3. D, E and J have become leaves and go, then B and F. A and C remain, the same center as the path gave.

Diameter 7 from H to K, center A and C, radius 4. Rooting the tree at A or at C gives height 4, the smallest possible, which is the answer to "Minimum Height Trees" for this tree.

Complexity, and where it comes from

Time: O(n) · Space: O(n)

Each BFS visits every vertex and every edge once, and a tree has n − 1 edges, so each pass is O(n). Following the parents back gives the path in O(n). Leaf peeling removes each vertex once and lowers each degree once, O(n) as well.

When to use Tree Diameter and Center, and when not to

Other ways to get diameters and centers.

AlternativePrefer it whenCost
BFS from every vertexGeneral unweighted graphs, where two BFS passes only give a lower bound. It also gives every eccentricity.O(n·m)
Tree DP over the two deepest branchesOne DFS is run over the tree anyway, for example with weights. At each vertex, add the two deepest child branches, and the best sum is the diameter.O(n)
Floyd–WarshallSmall weighted graphs where all pairwise distances are needed anyway.O(n³)

Common pitfalls

  • Two BFS on a graph with cycles. On a general graph the second BFS can return a path shorter than the true diameter. It is a fast lower bound and a good heuristic, called the 2-sweep, not an exact method.
  • Forgetting the weights. BFS counts edges. With non-negative weights use DFS or Dijkstra distances in both passes. With negative weights the farthest-vertex argument fails.
  • One center for an odd diameter. When the diameter is odd, the middle of the path is an edge, so the center is two adjacent vertices. Minimum Height Trees expects both roots in that case.

Frequently asked questions

Why does the farthest vertex from any start end a longest path?
Take a longest path x–y and the farthest vertex u from s. Since paths in a tree are unique, the path from s to u and the path x–y either share a vertex or are joined by a unique connecting path, and comparing lengths shows that u to x or u to y is at least as long as x–y. So u is an end of a longest path. The comparison needs unique paths, which only trees guarantee.
What is the difference between the center and the centroid?
The center minimises the largest distance to another vertex. The centroid minimises the size of the largest piece left when the vertex is removed. They can be different vertices, and each is one vertex or two adjacent ones.
How are the diameter and the radius related in a tree?
The radius is half the diameter, rounded up: r = ⌈d/2⌉. Here d = 7 and r = 4. In general graphs only r ≤ d ≤ 2r holds.

Related algorithms: Breadth-First Search, Tree Traversal (Pre, In, Post, Level), Lowest Common Ancestor (Binary Lifting), Prüfer Code, Floyd-Warshall Algorithm

An example graph: you can change it, or start blank.

Zoom Controls

31%
Nodes: 11
Edges: 10