Lesson 11 · Advanced structures and algorithms

Tree Diameter and Height

The diameter of a tree is the number of edges on its longest path. One post-order pass finds it: every node returns its height and records the path that bends at it.

Tree Diameter and Height concept diagramA visual explanation of the layout and operations shown in this lesson.the longest path between any two nodes need not touch the root1234564 → 2 → 1 → 3 → 6 spans 4 edges: at each node, left height + right height + 2
1

Diameter Is Not Height

The diameter of a tree is the number of edges on the longest path between any two nodes. The height of a node is the number of edges on the longest path from it straight down to a leaf. Height goes down from one node; the diameter runs between two.

A path in a tree goes up from one end to a highest node and then down to the other end. That highest node is the only place the path turns, so every path has exactly one bend point.

The trap is assuming the bend point is the root. In the tracer's 9-node tree the root has a single leaf on its left and a deep subtree on its right. The longest path, 6 edges, bends at node 3 inside that subtree; the best path through the root is only 5.

So the question becomes local: for each node, how long is the longest path that bends there? The diameter is the largest of those n answers.

Both ends of a longest path have only one neighbour. If an end had another neighbour off the path, stepping to it would make the path longer. In a rooted tree that means the ends are leaves, or the root when it has a single child.

  • A single node has diameter 0; an empty tree is 0 by convention
  • On a path-shaped tree (a chain) the diameter is n − 1 and one end may be the root
  • Balanced trees usually bend at the root, which is why tests on them miss the bug
2

The Formula at Each Node

Let L and R be the heights of a node's left and right subtrees. The longest path bending at the node goes as deep as possible on each side: L edges down the left, R down the right, plus the two edges from the node to its children. That is L + R + 2 edges.

Counting a missing child as height −1 makes this work everywhere. A leaf gets −1 + −1 + 2 = 0, and a node with one child of height 1 gets 1 + (−1) + 2 = 2.

Many solutions, including the code on this page, count a missing child as 0 instead. Then a leaf has height 1, the bent path is L + R and the height returned is 1 + max(L, R). Both conventions give the same diameter. Mixing them, for example −1 for null with L + R, is what makes answers come out one or two short.

Each node produces two different numbers. Its height, 1 + max(L, R), goes up to the parent, because a parent can only extend a path down one side. Its bent path, L + R + 2, goes into a running best and never upward: a path that already turned cannot be extended by an ancestor.

Returning the bent path instead of the height is the classic bug. On the tracer's tree node 3 would return 6, the root would compute 0 + 6 + 2 = 8, and no 8-edge path exists in a 9-node tree that is not a chain.

  • Up to the parent: height 1 + max(L, R)
  • Into the running best: bent path L + R + 2
  • For an n-ary tree, use the two largest child heights instead of L and R
3

One Post-Order Pass

  1. A missing child returns height −1
  2. Get L from the left child and R from the right child
  3. Set best = max(best, L + R + 2)
  4. Return 1 + max(L, R) to the parent
  5. After the root returns, best is the diameter in edges

A node needs both children's heights before it can compute anything, so the children must finish first. That is a post-order traversal; see tree traversals for the visiting orders.

The running best lives outside the recursion: a field, a closure variable or a one-element array, depending on the language. The recursion carries heights; the outside variable carries the answer.

Every node is visited once and does constant work, so the method is O(n). The slow version calls a separate height function at every node, which re-walks the same subtrees; on a chain of n nodes that is about n²/2 visits, O(n²).

Space is O(h) for the call stack: O(log n) on a balanced tree, O(n) on a chain. A chain of a million nodes overflows a recursive version in most languages, so use an iterative post-order there, or the two-pass method below.

For a general (n-ary) tree only one line changes: keep the two largest child heights and add them, plus 2. Everything else stays the same.

Key reference

Terms, operations, and practical uses

Definitions

  • Tree diameterThe number of edges on the longest path between any two nodes. It need not pass through the root.
  • Node heightThe number of edges on the longest path from the node down to a leaf.
  • Path lengthUsually counted in edges; some problems count nodes, which is one more.

Recursive approach

  • Post-orderCompute the left and right subtree heights before the node itself.
  • Bent pathL + R + 2 with a null child as −1, or L + R with a null child as 0.
  • Running bestA variable outside the recursion keeps the largest bent path seen so far.

Two-pass approach

  • First passBFS or DFS from any node finds the farthest node u.
  • Second passBFS or DFS from u finds the farthest node v; dist(u, v) is the diameter.
  • When it appliesAny tree with non-negative edge weights; no root and no recursion needed.
Implementation

Code in Python, C++ and Java

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

class Solution:
    def diameterOfBinaryTree(self, root):
        self.dia = 0
        def height(node):
            if not node:
                return 0
            l = height(node.left)
            r = height(node.right)
            self.dia = max(self.dia, l + r)
            return 1 + max(l, r)
        height(root)
        return self.dia

root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))
print('Diameter:', Solution().diameterOfBinaryTree(root), 'edges')
#include <iostream>
#include <algorithm>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int x, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(x), left(l), right(r) {}
};

class Solution {
    int dia = 0;
    int height(TreeNode* node) {
        if (!node) return 0;
        int l = height(node->left);
        int r = height(node->right);
        dia = max(dia, l + r);
        return 1 + max(l, r);
    }
public:
    int diameterOfBinaryTree(TreeNode* root) {
        height(root);
        return dia;
    }
};

int main() {
    TreeNode* root = new TreeNode(1,
        new TreeNode(2, new TreeNode(4), new TreeNode(5)),
        new TreeNode(3, new TreeNode(6), new TreeNode(7)));
    cout << "Diameter: " << Solution().diameterOfBinaryTree(root) << " edges\n";
}
public class Main {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int x) { val = x; }
        TreeNode(int x, TreeNode l, TreeNode r) { val = x; left = l; right = r; }
    }

    int dia = 0;
    int height(TreeNode node) {
        if (node == null) return 0;
        int l = height(node.left);
        int r = height(node.right);
        dia = Math.max(dia, l + r);
        return 1 + Math.max(l, r);
    }
    public int diameterOfBinaryTree(TreeNode root) {
        height(root);
        return dia;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,
            new TreeNode(2, new TreeNode(4), new TreeNode(5)),
            new TreeNode(3, new TreeNode(6), new TreeNode(7)));
        System.out.println("Diameter: " + new Main().diameterOfBinaryTree(root) + " edges");
    }
}
Watch it run

Step through it

Running on 9-node tree, root 1

9 nodes, root 1123456789startbest0null height−1orderpost-ordergoal: longest path, in edges
Step 1

The tree and the plan

Every node will hand two numbers out: its height goes up to the parent, and the path that bends at it, L + R + 2 edges, is compared with a running best. A missing child counts as height −1, so a leaf needs no special case. Children are finished before their parent: post-order.

Output
1 / 14
4

Edges or Nodes, and the Two-Pass Method

The most common wrong answer is off by one: the diameter can be counted in edges or in nodes. A path through 7 nodes has 6 edges. Textbooks and most judges count edges; some interview questions count nodes. A single-node tree settles which one a problem wants: 0 edges or 1 node.

A second algorithm works when the tree is given as an edge list with no root. Run a BFS or DFS from any node and find the farthest node u. Run again from u and find the farthest node v. The distance from u to v is the diameter: two passes, O(n) each.

It works because the farthest node from any starting point is always an end of some longest path. On the tracer's tree, starting from node 2 reaches 8 or 9 at distance 5; starting again from 8 reaches 9 at distance 6, the same answer as the post-order pass.

The trick needs a tree with non-negative edge weights; with weights, measure distances with DFS sums instead of BFS levels. With negative weights, or on a graph with cycles, the first pass can end at the wrong node and the answer is no longer guaranteed.