Tech Interview RoomStudy guides

Trees

Diameter of a binary tree. Compare recomputing heights and a single postorder pass.

Intermediate · 2 min read · Lesson 5 of 5 in Trees

Problem

The diameter is the number of edges on the longest path between any two nodes (it may not pass through the root).

Pattern

Postorder "return one thing, record another": each call returns the height of its subtree to its parent, and on the way updates a global answer using both children's heights.

java
final class DNode {
    DNode left, right;
    DNode(DNode left, DNode right) { this.left = left; this.right = right; }
    static DNode leaf() { return new DNode(null, null); }
}

Approach 1: Height computed from scratch at every node (feasible, O(n²) worst case)

java
class DiameterNaive {
    static int height(DNode n) { return n == null ? 0 : 1 + Math.max(height(n.left), height(n.right)); }
    static int diameter(DNode n) {
        if (n == null) return 0;
        int through = height(n.left) + height(n.right);
        return Math.max(through, Math.max(diameter(n.left), diameter(n.right)));
    }
}

Approach 2: One postorder pass (O(n)) — optimal

java
class DiameterOnePass {
    private int best;

    static int diameter(DNode root) {
        DiameterOnePass d = new DiameterOnePass();
        d.height(root);
        return d.best;
    }

    private int height(DNode n) {
        if (n == null) return 0;
        int l = height(n.left), r = height(n.right);
        best = Math.max(best, l + r);                            // longest path through this node
        return 1 + Math.max(l, r);
    }
}

class DiameterDemo {
    public static void main(String[] args) {
        //      1
        //     / \
        //    2   3
        //   / \
        //  4   5
        DNode root = new DNode(new DNode(DNode.leaf(), DNode.leaf()), DNode.leaf());
        System.out.println(DiameterNaive.diameter(root) + " " + DiameterOnePass.diameter(root));   // 3 3
        DNode chain = null;
        for (int i = 0; i < 2000; i++) chain = new DNode(chain, null);                             // skewed tree
        System.out.println(DiameterOnePass.diameter(chain));                                        // 1999
    }
}

Feasible → optimal

Recomputing heights is O(n²) on skewed trees; a single postorder pass that returns heights and records the best left + right is O(n). For extremely deep trees, convert to an iterative postorder to avoid stack overflow.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): check whether a tree is height-balanced.

Same postorder: return the height, or -1 as soon as a subtree is unbalanced (|l - r| > 1), and propagate -1 upwards. O(n) instead of the O(n²) "compute height at every node" approach.

Related (same pattern): binary tree maximum path sum.

Return to the parent the best single-branch sum node.val + max(0, left, right) and record node.val + max(0, left) + max(0, right) as a candidate answer at each node. O(n). Negative branches are dropped with max(0, ...).