Tree Diameter
Tree edges:
Diameter
–
Pseudocode
1a ← any vertex (here the root)2BFS from a; b ← the vertex farthest from a3BFS from b; c ← the vertex farthest from b4the path from b to c is a longest path: the diameter
BFS layers
0
Diameter
0
2BFS distance (blue)b / cends of the diameterthe longest path
What is the Diameter of a Tree?
The diameter of a tree is the length of its longest path: the two nodes that are farthest apart, counted in edges. In a network shaped like a tree it is the worst-case number of hops a message needs.
Checking every pair would be slow, but trees allow a neat trick with two breadth-first searches. From any vertex, the farthest vertex b is always one end of a longest path. A second BFS from b then finds the farthest vertex c, the other end.
Farthest from anywhere is one end; farthest from that end is the other.
Using the Visualizer
- • Blue numbers are BFS distances; the blue wave shows the layer being reached.
- • The first BFS starts at 0 and finds b; the second starts at b and finds c. The green path is the diameter.
- • Type a tree as edges like 0-1, 0-2, 1-3 and press Apply, or try a Random tree.
How It Works
1. Start anywhere
Pick any vertex a (here: 0).
2. First BFS
Find b, the vertex farthest from a.
3. Second BFS
From b, find c, the vertex farthest from b.
4. Answer
dist(b, c) is the diameter, and following the BFS parents gives the path.
Only for trees: in a general graph the farthest vertex from a random start is not always an end of the longest shortest path, so this shortcut can fail.
Implementation
Properties & Complexity
Time Complexity
- • Two BFS: O(n)
- • Brute force (BFS from every vertex): O(n²)
Space & Properties
- • Space: O(n)
- • Weighted trees: same trick with DFS distances, or a DP on the tree
Where It Is Used
- • Networks: worst-case delay in a tree-shaped network
- • Tree centre: the middle of the diameter minimises the farthest distance
- • Competitive programming: a classic building block
Limitations
- • Trees only: not valid for graphs with cycles
- • Negative weights break the trick