Diameter of Binary Tree

Find the number of edges on the longest path between any two nodes of a binary tree.

Given the root of a binary tree, return its diameter: the number of edges on the longest path between any two nodes. A path follows the links between parents and children and visits each node at most once. It does not have to pass through the root.

Example 1
Input: root = [1, 2, 3, 4, 5]
Output: 3
Explanation: 4 → 2 → 1 → 3 (or 5 → 2 → 1 → 3).
Example 2
Input: root = [1, 2]
Output: 1
Solution

The Idea

Draw Example 1 on paper, one row at a time: 1 in the first row, 2 and 3 in the second, 4 and 5 in the third. Node 1 sits at the top, as the root. Its children are 2 and 3, and 2 has two children of its own, 4 and 5. Each line from a parent to a child is an edge.

Walking from 4 to 3 means going up from 4 to 2, up again to 1, then down to 3. That walk crosses three edges. No two nodes in this tree are farther apart, so the diameter is 3.

On that walk, 1 is the highest node: the path climbs up to it and then goes down the other side. Every path has such a highest node where it turns. On the short path from 2 down to 4, the highest node is 2 itself.

So does the longest path always turn at the root? Look at the picture below. It draws the tree [1, 2, null, 3, 4, 5, null, null, 6], where null marks a missing child, so 1 has no right child and 4 has no left child.

The tree 1, 2, null, 3, 4, 5, null, null, 6. The longest path 5, 3, 2, 4, 6 is drawn in orange and has 4 edges. Its highest node is 2, with left height 2 for nodes 3 and 5, and right height 2 for nodes 4 and 6. The longest path from the root 1 is 1, 2, 3, 5, with 3 edges.

The orange path 5, 3, 2, 4, 6 crosses four edges, and its highest node is 2, not the root. The box labelled "longest path from root 1" shows the best a path from the root can do here: 1, 2, 3, 5, three edges. The longest path can turn at any node, so every node has to be checked.

How long is the longest path that turns at one node? It goes down as far as it can on the left side, and as far as it can on the right side. Node 3, together with everything below it, is the left subtree of 2. Nodes 4 and 6 form its right subtree.

Count the nodes on the longest way down a subtree, and you get its height. In the picture, "left height 2" counts nodes 3 and 5, and "right height 2" counts nodes 4 and 6. Going from 2 down to 5 crosses exactly 2 edges, one per node, so the path that turns at 2 has 2 + 2 = 4 edges.

So the diameter is the largest value of left height plus right height, taken over all the nodes. And heights are easy to build from the bottom up: a node's height is one more than the taller of its two subtrees. One walk over the tree can produce every height and every sum.

Solution Approach

Turning that idea into code means seeing why working out each node's two heights separately is slow, then settling three things: the order in which nodes are visited, how a height is counted, and where the longest path found so far is kept.

Working out each height separately

Why not work out the two heights of each node separately? A method that walks a subtree and returns its height is short to write. But calling it afresh at every node walks the lower nodes again and again. In a tree shaped like one long chain of n nodes, that adds up to about n²/2 steps.

Visiting children before their parent

How can each height be worked out only once? Ask the children first. A recursive method height(node) calls itself on the left child and on the right child, and only then deals with the node, which now knows both heights. Visiting the children before their parent like this is called a post-order traversal.

Counting height in nodes

Why count nodes rather than edges? A missing child, null, has height 0, and a node with no children has height 1. With that choice, left height plus right height is exactly the number of edges of the path that turns at the node. A node with no children gives 0 + 0 = 0, a path with no edges.

In Example 2, node 1 has the left child 2 and no right child. The path that turns at 1 has 1 + 0 = 1 edge, which is the expected output.

Keeping the longest path in a field

Where does the answer go? height must return the height, because the parent needs it, and a parent can only extend a path down one of its sides. So the longest path found so far lives in a field, best, which every call to height updates with left height plus right height.

Java Solution

The method diameterOfBinaryTree works in these steps:

  1. First, set the field best back to 0, so a second call on the same object does not start from the first call's answer. Then call height(root), which walks the whole tree.
  2. Inside height, a null node returns 0, since an empty subtree has no nodes.
  3. For a real node, call height on node.left and on node.right first, and keep the results in left and right.
  4. The path that turns at this node has left + right edges. If that beats best, it becomes the new best.
  5. Return 1 + Math.max(left, right), the node's own height, so its parent can use it.
  6. Once height(root) has returned, every node has been checked, and diameterOfBinaryTree returns best as the diameter.

The class also has a small TreeNode class and a build method that makes a tree from the row-by-row form. The main method runs both examples, the tree from the picture, a single node, an empty tree, and a chain of four nodes that each hang to the left.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

public class DiameterOfBinaryTree {

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

    private int best = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        best = 0;
        height(root);
        return best;
    }

    // Returns the height in nodes and records the longest path that turns at each node.
    private int height(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = height(node.left);
        int right = height(node.right);
        best = Math.max(best, left + right);  // edges of the path that turns at this node
        return 1 + Math.max(left, right);
    }

    // Builds a tree from the row-by-row form, with null for a missing child.
    static TreeNode build(Integer[] values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = queue.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                queue.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                queue.add(parent.right);
            }
            i++;
        }
        return root;
    }

    public static void main(String[] args) {
        DiameterOfBinaryTree solver = new DiameterOfBinaryTree();
        Integer[][] trees = {
            {1, 2, 3, 4, 5},
            {1, 2},
            {1, 2, null, 3, 4, 5, null, null, 6},
            {1},
            {},
            {1, 2, null, 3, null, 4}
        };
        for (Integer[] tree : trees) {
            int d = solver.diameterOfBinaryTree(build(tree));
            System.out.println(Arrays.toString(tree) + " -> " + d);
        }
    }
}

Running it prints:

Output
[1, 2, 3, 4, 5] -> 3
[1, 2] -> 1
[1, 2, null, 3, 4, 5, null, null, 6] -> 4
[1] -> 0
[] -> 0
[1, 2, null, 3, null, 4] -> 3

Example 1 gives 3 and Example 2 gives 1, as expected. Look at the third line: the tree from the picture gives 4, the path 5, 3, 2, 4, 6 that turns at node 2. A separate check that adds the two heights only at the root returns 3 for this same tree, so it misses the longest path.

The single node [1] gives 0, because a path of one node has no edges. The empty tree [] also gives 0, since height(null) returns at once. The last line is the chain 1, 2, 3, 4: its longest path turns at the root, with left height 3 and right height 0, so it prints 3.

Complexity

The work is one call of height for every node, plus one for every missing child.

  • Time: O(n), because height runs once for each of the n nodes and once for each null child, and each call does a fixed amount of work around its two recursive calls.
  • Space: O(h), where h is the height of the whole tree, because the recursion keeps one open call for each node between the root and the node being visited; a chain like the last test makes h equal to n.

Weighting the path by node values instead of counting edges gives Binary Tree Maximum Path Sum.