AlgoTales · Roadmap

Diameter

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The diameter of a tree is the longest path between any two nodes, which does not have to pass through the root. It tells you the worst-case distance across the structure, such as the longest trip between two points in a network.

Practical use cases

  • Web app: Worst-case delay in a network map. A monitoring page draws servers as a tree and wants the slowest possible route between any two machines. The diameter gives the answer. If it is 9 hops, the team knows the worst message travels through 9 links and can plan timeouts accordingly.
  • Web app: Longest chain in a referral tree. A referral program shows who invited whom, and the marketing team asks how long the longest chain between two members is. Each member asks the people they invited how long their chains are, and the two longest add up to the answer. That tells the team whether the programme spreads widely or only along one long line.
  • System: Road and cable planning. Planners laying cable or roads in a tree layout look at the diameter to find the farthest pair of towns. The longest pair, not the average pair, decides the worst delay or the longest wait a customer in the farthest town might face.

The story: The Longest Walk in the Mohalla

The Ganesh Chaturthi committee in Mira's mohalla wanted to hang a long string of marigold garlands along the longest possible walk between two houses. The lanes of the mohalla branched like a tree: one main lane, then side lanes, then little gullies.

Uncle Raju started measuring every pair of houses with a measuring tape. With forty houses, that was hundreds of pairs, and his tape was already tangled. Mira had a better idea: "Every long walk has a highest point, a junction where it turns from going up to going down. At that junction, the walk is the deepest path on the left plus the deepest path on the right."

So she asked every junction two quick questions: "How far does your left side go?" and "How far does your right side go?" She added the two answers, wrote the total on a sticky note, and kept the biggest note. A junction answered its own parent with just the taller side plus one.

One walk through the whole mohalla gave the longest garland route: from the farthest gully on the left, up over the top, and down to the farthest gully on the right. That longest walk is the diameter. The tape was saved.

How to spot this problem, and where you need it

You need the longest path between any two points in a tree-shaped structure, and it may not pass through the top node, so checking only from the root misses it.

Signs you need it

  • The problem says "diameter", "longest path between any two nodes" or "farthest pair".
  • You need a worst-case distance for a network, family tree or referral chain.
  • Your first try measured only paths through the root and gave an answer that was too small for some trees.

Where to use it in a project

  • Network and infrastructure dashboards that report the worst-case hops between two machines.
  • Referral, organisation or family trees where you need the longest chain across the whole structure.

The solution

At each node, work out the height of its left arm and its right arm. The longest path that turns at this node is left plus right. Keep a running best of this number over all nodes. While doing this, return the larger arm plus one to the parent so it can do the same. After visiting every node once, the best value is the diameter.

Payoff: Before: trying every pair of nodes, millions of checks. After: a single walk over the tree that visits each node once.

Explain it like I am 8

Imagine the longest walk you could take in a tree without ever walking the same lane twice. Every such walk has a "turning node" at its top. So at every node ask: how long is my left arm, how long is my right arm? Add them. The biggest sum anywhere is the answer.

How it works, step by step

  1. Define each node's arms: the left arm is 0 if there is no left child, otherwise (left height + 1). Same for the right arm.
  2. If the longest walk bends at this node, its length is left arm + right arm. Write it down and keep the maximum seen.
  3. Return the node's height (taller arm) to its parent, exactly like in the height lesson.
  4. Do it for all nodes in one post-order sweep (children before parent).
  5. The biggest total is the diameter. It may bend at the root, or lower down.

The code in four languages

PHP

<?php
class TreeNode {
    public ?TreeNode $left = null;
    public ?TreeNode $right = null;
    public function __construct(public int $val) {}
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree(): TreeNode {
    $root = new TreeNode(1);
    $root->left = new TreeNode(2);
    $root->right = new TreeNode(3);
    $root->left->left = new TreeNode(4);
    $root->left->right = new TreeNode(5);
    $root->right->right = new TreeNode(6);
    $root->left->right->left = new TreeNode(7);
    return $root;
}

function diameter(?TreeNode $root): int {
    $best = 0;
    // walk() returns the height of a node, and updates $best on the way.
    $walk = function (?TreeNode $n) use (&$walk, &$best): int {
        if ($n === null) return -1;
        $leftArm  = $walk($n->left) + 1;       // 0 when there is no left child
        $rightArm = $walk($n->right) + 1;
        $best = max($best, $leftArm + $rightArm);   // a path that bends at this node
        return max($leftArm, $rightArm);              // height of this node
    };
    $walk($root);
    return $best;
}

echo 'Diameter (edges): ' . diameter(sampleTree()) . PHP_EOL;   // 5 : 7-5-2-1-3-6

JavaScript

class TreeNode {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree() {
  const root = new TreeNode(1);
  root.left = new TreeNode(2);
  root.right = new TreeNode(3);
  root.left.left = new TreeNode(4);
  root.left.right = new TreeNode(5);
  root.right.right = new TreeNode(6);
  root.left.right.left = new TreeNode(7);
  return root;
}

function diameter(root) {
  let best = 0;
  // walk() returns the height of a node, and updates best on the way.
  function walk(n) {
    if (n === null) return -1;
    const leftArm = walk(n.left) + 1;          // 0 when there is no left child
    const rightArm = walk(n.right) + 1;
    best = Math.max(best, leftArm + rightArm); // a path that bends at this node
    return Math.max(leftArm, rightArm);        // height of this node
  }
  walk(root);
  return best;
}

console.log('Diameter (edges): ' + diameter(sampleTree()));   // 5 : 7-5-2-1-3-6

Java

import java.util.*;
import java.util.stream.*;

public class Main {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    // The example tree:      1
    //                       /   \
    //                      2     3
    //                     / \     \
    //                    4   5     6
    //                       /
    //                      7
    static TreeNode sampleTree() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        root.left.right.left = new TreeNode(7);
        return root;
    }

    // Returns the height of a node, and updates best[0] on the way.
    static int walk(TreeNode n, int[] best) {
        if (n == null) return -1;
        int leftArm = walk(n.left, best) + 1;                 // 0 when there is no left child
        int rightArm = walk(n.right, best) + 1;
        best[0] = Math.max(best[0], leftArm + rightArm);      // a path that bends at this node
        return Math.max(leftArm, rightArm);                   // height of this node
    }

    static int diameter(TreeNode root) {
        int[] best = {0};
        walk(root, best);
        return best[0];
    }

    public static void main(String[] args) {
        System.out.println("Diameter (edges): " + diameter(sampleTree()));   // 5 : 7-5-2-1-3-6
    }
}

Go

package main

import (
	"fmt"
)

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// The example tree:      1
//
//	   /   \
//	  2     3
//	 / \     \
//	4   5     6
//	   /
//	  7
func sampleTree() *TreeNode {
	root := &TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Right = &TreeNode{Val: 3}
	root.Left.Left = &TreeNode{Val: 4}
	root.Left.Right = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}
	root.Left.Right.Left = &TreeNode{Val: 7}
	return root
}

func diameter(root *TreeNode) int {
	best := 0
	// walk returns the height of a node, and updates best on the way.
	var walk func(n *TreeNode) int
	walk = func(n *TreeNode) int {
		if n == nil {
			return -1
		}
		leftArm := walk(n.Left) + 1 // 0 when there is no left child
		rightArm := walk(n.Right) + 1
		best = max(best, leftArm+rightArm) // a path that bends at this node
		return max(leftArm, rightArm)      // height of this node
	}
	walk(root)
	return best
}

func main() {
	fmt.Println("Diameter (edges):", diameter(sampleTree())) // 5 : 7-5-2-1-3-6
}

Time: O(n) · Extra space: O(h). A single post-order sweep visits each node once. Trying every pair of nodes would be far slower.

Watch out for

  • Assuming the longest path always passes through the root. A deep, bushy branch lower down can win, so check every node.
  • Computing height again inside every node (a second recursion). That turns O(n) into O(n²); return the height while you go.
  • Mixing nodes and edges. 6 nodes on the path means 5 edges. Make sure your answer matches what was asked.

Quick check

  1. At one node, how long is the longest path that bends there?
    • Left arm + right arm
    • The bigger of the two arms
    • The height of the node
  2. What is the diameter of our example tree (in edges)?
    • 4
    • 5
    • 6
    • 3
  3. What does each node return to its parent?
    • Its diameter
    • Its height
    • Its number of nodes