Scrivio Interview library
TreesTrees and binary search treesReported 28 times · 15 min read · updated 14 November 2026

Find the diameter of a binary tree, the longest path between any two of its nodes.

1What the diameter of a tree means

Think of a family tree drawn on a wall, or the branches of a real tree. Suppose an ant wants to walk along the branches between two leaves, never walking the same piece of branch twice. Some walks are short, from one leaf to its neighbour. Some are long, down one side of the tree, over the top and down the other. The diameter is the length of the longest walk the ant could make.

In tree words, a node is one circle in the drawing, and an edge is the line joining a node to its child. A binary tree is one where each node has at most two children, a left and a right. A path is a chain of nodes joined by edges, with no node used twice. The diameter is the number of edges on the longest path between any two nodes.

Our example tree has root 1, with children 2 and 3, and node 2 has children 4 and 5. Let us measure a few paths by hand, counting the lines walked. 4 -> 2 -> 5 has 2 edges. 4 -> 2 -> 1 has 2 edges. 4 -> 2 -> 1 -> 3 has 3 edges, and so does 5 -> 2 -> 1 -> 3. There is no longer one, so the diameter is 3.

This question can feel slippery at first, because a path may start anywhere and end anywhere. But look at any path you drew. It climbs up from one end, reaches a highest node, and goes down to the other end. Every path has exactly one highest node, the place where it bends. That simple fact is what makes the problem manageable.

PictureThe example tree and its longest path

Node 1 is the root. The marked nodes form one longest path, 4 -> 2 -> 1 -> 3, which has 3 edges.

  1. 12345
    nodes
    5
    diameter
    3 edges
    one path
    4 -> 2 -> 1 -> 3

    1The longest path runs 4 -> 2 -> 1 -> 3 and uses 3 edges, so the diameter is 3. The path 5 -> 2 -> 1 -> 3 is just as long.

What to assume

Do we count edges or nodes?
We count edges, the usual convention.
Must the path pass through the root?
No.
What is the answer for an empty tree or a single node?
We say 0 for both.
How deep can the tree be?
Possibly very deep. The main solution is written for trees of ordinary depth; a single chain of a hundred thousand nodes needs separate care.

A careful candidate asks a few questions first. Do we count edges or nodes? We count edges, the usual convention, and note that counting nodes simply adds one. Must the path pass through the root? No, and this is the trap many people fall into, as we will see. What is the answer for an empty tree or a single node? We say 0 for both. How deep can the tree be? Deep enough that we should mention recursion depth at the end.

2How to recognise a tree problem solved from the bottom up

A beginner's first idea is often to start at the root, go as deep as possible to the left, as deep as possible to the right, and add the two. On our example that gives the right answer, 3. It feels finished, but this idea is wrong on other trees.

The picture shows such a tree. Its root has only a left child, and the long path lives entirely below that child. The path bending at the root has 3 edges, but the path bending at node 2 has 4. So the first clue in the question is the phrase between any two of its nodes. It tells us the path can bend at any node, not only at the root, so we must consider every node as a possible bending point.

Step throughA tree whose longest path never touches the root

The root 1 has only a left child. Compare the longest path that bends at the root with the one that bends at node 2.

  1. 124589
    bends at
    node 1, the root
    left height
    2
    right height
    -1, empty
    path
    2 + (-1) + 2 = 3

    1The longest path that bends at the root 1 goes down to 8 or 9 on the left and nowhere on the right: 1 -> 2 -> 4 -> 8, only 3 edges.

  2. 124589
    bends at
    node 2
    left height
    1
    right height
    1
    path
    1 + 1 + 2 = 4
    diameter
    4

    2The path that bends at node 2 goes down both sides: 8 -> 4 -> 2 -> 5 -> 9, which is 4 edges. This is the diameter, and the root is not on it.

The second clue is the word longest, together with what we found by hand. The longest path bending at a node goes down as far as possible on the left and as far as possible on the right. How far down we can go from a node is called its height, the number of edges on the longest downward path from it. So the path bending at a node has length height of left child + height of right child + 2, the 2 being the edges from the node to its two children. Everything we need at a node comes from its two subtrees, the smaller trees hanging below it.

These clues point to the trees pattern, and in particular to a bottom-up recursion. A recursion is a method that calls itself on smaller pieces, here on the left and right subtrees. Bottom-up means the children finish their work before the parent uses it. Visiting the children first and the node last has a name, post-order. The rule to carry to new problems is this. When the answer at a node combines information from both subtrees, write one post-order recursion that returns one value up to the parent and updates a separate best answer on the way. The same shape solves the maximum path sum, the balanced tree check and the longest path of equal values.

Two other ideas look possible but fit less well. Breadth-first search, which visits the tree level by level, is the other standard traversal, but it cannot combine a left branch with a right branch at the node where they meet. Treating the tree as a general graph and running two searches does find the diameter, but it needs links from each node back to its parent, which a binary tree does not give us.

3The brute force, measuring heights again at every node

The honest first attempt follows our observation word for word. For every node, compute the height of its left subtree and of its right subtree with a separate method, add 2, and keep the largest result. The diameter of a tree is then the largest of three things: the path bending at the root, the diameter of the left subtree, and the diameter of the right subtree. This brute force is correct, and it is a perfectly good first thing to say aloud.

Java
static int height(Node n) { // edges on the longest way down
if (n == null) return -1;
return 1 + Math.max(height(n.left), height(n.right));
}
static int diameterSlow(Node n) {
if (n == null) return 0;
int through = height(n.left) + height(n.right) + 2; // path bending at n
return Math.max(through, Math.max(diameterSlow(n.left), diameterSlow(n.right)));
}

The height method itself is a small recursion. An empty subtree has height -1, a choice that makes a leaf come out at -1 + 1 = 0, which is right, because a leaf has no edges below it.

Now let us count. On our five-node example, the height calls visit 6 nodes in all: nodes 4 and 5 are each measured twice, once while measuring node 2 for the root and again when we stand on node 2 itself. That does not look bad. But take a tree shaped like a chain, each node having only a left child. With 5 nodes the height calls visit 10 nodes, and with 1,000 nodes they visit 499,500. The node at depth d has its whole subtree measured again, about n - d nodes, so the total is about n squared over 2, which is O(n squared). The space is O(h), where h is the height of the tree, for the waiting recursive calls.

Where is the waste? The height of a subtree never changes, yet the brute force recomputes it once for every ancestor above it. When we stand on node 2 and measure the height of node 4, we have already measured it before, while measuring node 2 for the root. If each node could hand its height to its parent once, nobody would ever need to measure it again.

4Getting to one pass, one observation at a time

Let us turn the waste into a plan. The parent needs its children's heights, so the children should be measured first and should report their heights upward. That is the post-order order. A method height(node) first calls height(node.left) and height(node.right), and only then works on the node itself.

Now notice what that method knows at that moment. It holds the left height and the right height of this very node, exactly the two numbers needed for the path that bends here. So, while it is there, it can work out left + right + 2 and compare it with the best path found so far, kept in a variable called best. No extra visit is needed. Then it returns its own height, 1 + max(left, right), to its parent.

Here is the question a beginner almost always asks at this point. Why does the method return the height and not the path length? Surely the path is what we want? Let us think about what the parent can use. The parent wants to extend a path down into this subtree. A path that already bends here, going down both sides, cannot be extended upward, because a path through the parent would then have to visit this node twice. The parent can only continue one branch, the deeper one, and that is exactly the height. So we return one thing, the height, and record a different thing, the bending path, in best.

Why is this correct? Every path has exactly one highest node, and when the recursion stands on that node, it adds the two deepest branches, which is the longest path that bends there. Since every node is visited, the longest path overall is recorded when the recursion reaches its highest node. The -1 for an empty child keeps everything uniform. A leaf gets -1 + -1 + 2 = 0, and a node with one leaf child gets 0 + -1 + 2 = 1, the single edge to that child.

The mistake beginners most often make here is to return left + right + 2 from the method, or to return the bigger of the path and the height. Both mix up the two quantities, and the answers come out too large, because a parent ends up building on a path that already bends below it.

5Watching the recursion climb back up the example tree

The picture follows height on our example tree. The first frame shows the calls going down to node 4, because nothing can finish until a leaf is reached. After that, each frame shows one node finishing, in post-order, children before parents. The panel shows the heights the node received, the path that bends at it, best, and the height it returns.

Watch two numbers separately, the value returned, which climbs up the tree, and best, which only ever grows.

Step throughOne post-order pass over the example tree

Nodes finish in post-order, children before parents. Each finished node has reported its height upward and offered the path that bends at it.

  1. 12345
    calls waiting
    1, 2, 4
    best
    0

    1diameter sets best to 0 and calls height(1). Before node 1 can do anything it asks its left child, 2, and node 2 asks node 4 first.

  2. 12345
    node
    4
    heights L, R
    -1 and -1
    path here
    -1 + -1 + 2 = 0
    best
    0
    returns
    0

    2height(4) asks both children, which are empty and answer -1. The path bending at 4 is -1 + -1 + 2 = 0 edges. best stays 0, and 4 returns 0.

  3. 12345
    node
    5
    heights L, R
    -1 and -1
    path here
    -1 + -1 + 2 = 0
    best
    0
    returns
    0

    3Node 5 is also a leaf: both children answer -1, its path is 0 edges, and it returns height 0 to node 2.

  4. 12345
    node
    2
    heights L, R
    0 and 0
    path here
    0 + 0 + 2 = 2
    best
    2
    returns
    1

    4Both children of 2 have answered 0. The path bending at 2 is 0 + 0 + 2 = 2 edges, 4 -> 2 -> 5, so best becomes 2. Node 2 returns 1 + max(0, 0) = 1.

  5. 12345
    node
    3
    heights L, R
    -1 and -1
    path here
    -1 + -1 + 2 = 0
    best
    2
    returns
    0

    5The recursion now goes to the right child of the root. Node 3 is a leaf, so its path is 0 edges, best stays 2, and it returns 0.

  6. 12345
    node
    1
    heights L, R
    1 and 0
    path here
    1 + 0 + 2 = 3
    best
    3
    returns
    2

    6The root has heard 1 from the left and 0 from the right. The path bending here is 1 + 0 + 2 = 3 edges, which beats 2, so best becomes 3. It returns 2.

  7. 12345
    diameter
    3
    visits
    5, one per node

    7height(1) has returned, so diameter returns best, which is 3. The path that won bends at the root: 4 -> 2 -> 1 -> 3.

Let us read the important frames back. Nodes 4 and 5 are leaves, so each reports height 0. At node 2 the two reports meet, and the path bending there is 0 + 0 + 2 = 2, the path 4 -> 2 -> 5. best becomes 2, but node 2 returns only 1 to its parent, because the root can continue just one of those branches.

Node 3 reports 0. At the root, the left report is 1 and the right report is 0, so the path bending at the root is 1 + 0 + 2 = 3, which beats 2. best becomes 3. Each node finished exactly once, five visits for five nodes, compared with six for the brute force here and 499,500 on a long chain.

Try the same reading on the tree in the earlier picture. There node 2 offers 1 + 1 + 2 = 4, while the root offers only 2 + (-1) + 2 = 3, so best keeps the 4 that node 2 recorded. The root never has to be on the path.

6The complete Java program

Here is the full program. It has a small Node class, the public diameter method, and the private height helper that does the work. main runs our example, the tree from the earlier picture whose longest path avoids the root, a single node and an empty tree, and each comment shows what that line prints.

Java
public class TreeDiameter {
static class Node {
int val;
Node left, right;
Node(int val, Node left, Node right) { this.val = val; this.left = left; this.right = right; }
Node(int val) { this(val, null, null); }
}
private static int best; // longest path seen so far, counted in edges
static int diameter(Node root) {
best = 0;
height(root);
return best;
}
// Height in edges counted from the node down; an empty tree has height -1.
private static int height(Node node) {
if (node == null) return -1;
int left = height(node.left);
int right = height(node.right);
best = Math.max(best, left + right + 2); // the longest path that bends at this node
return 1 + Math.max(left, right);
}
public static void main(String[] args) {
// 1
// / \
// 2 3
// / \
// 4 5
Node root = new Node(1, new Node(2, new Node(4), new Node(5)), new Node(3));
System.out.println(diameter(root)); // 3
// The longest path 8 -> 4 -> 2 -> 5 -> 9 never touches the root 1.
Node side = new Node(1, new Node(2, new Node(4, new Node(8), null),
new Node(5, null, new Node(9))), null);
System.out.println(diameter(side)); // 4
System.out.println(diameter(new Node(7))); // 0
System.out.println(diameter(null)); // 0
}
}

Let us read it in the order it runs. diameter first sets best to 0. This matters, because best is a static field shared by every call, and without the reset the second tree would start with the 3 left over from the first. Then it calls height(root) and ignores the value returned, because it wants best, not the height of the root.

Inside height, the first line handles an empty subtree by returning -1. Then the two recursive calls measure the left and right subtrees; by the time they return, every node below has already offered its own bending path to best. The line best = Math.max(best, left + right + 2) offers the path that bends at this node. Finally return 1 + Math.max(left, right) gives the parent our height, one edge more than our deeper child.

So main prints 3 for our example and 4 for the second tree, where the path 8 -> 4 -> 2 -> 5 -> 9 never touches the root. A single node gives -1 + -1 + 2 = 0, and an empty tree returns 0 straight away. A static field keeps the program short, but it is not safe if two threads call diameter at once; in production we would pass a small holder object, or an int array of length one, into the helper.

7How much it costs, and the cases at the edges

Let us count on the example first. Each of the five nodes was finished exactly once, with two recursive calls, one addition and two comparisons. For n nodes the work is a constant amount per node, so the time is O(n). We cannot do better, because any node might lie on the longest path.

The space is the recursion itself. Each call waits while its children are measured, so the number of waiting calls is at most the height of the tree plus one, written O(h). For a well balanced tree h is about log n, small even for a million nodes. For a tree shaped like a chain, h is n - 1, and a chain of a hundred thousand nodes can overflow Java's default call stack with a StackOverflowError. For such inputs we would rewrite it with an explicit stack of our own.

Comparing the approaches
ApproachTimeExtra space
Brute force: a separate height call at every nodeO(n^2) on a chainO(h)
One post-order pass returning heightsO(n)O(h)

The edge cases need no special code. An empty tree returns 0, because best starts at 0 and height returns at once. A single node offers a path of 0 edges and returns 0. A node with only one child works through the -1 for the missing side. And a tree whose longest path avoids the root, our second example, works because every node offers its own bending path, not only the root.

8Follow-up questions

How would you return the diameter counted in nodes instead of edges?

A path with k edges has k + 1 nodes, so the simplest change is to return best + 1, with care for the empty tree, which has no nodes at all and should give 0. Another way is to measure height in nodes, with 0 for an empty subtree, and record left + right + 1 at each node. Both are the same idea; we only have to say clearly which convention we use.

What if a node can have any number of children?

The path bending at a node still goes down its two deepest branches, so we look at the heights of all its children and keep the two largest. The path is then the largest + the second largest + 2, and the node returns 1 + the largest. If a node has only one child, the second largest is the -1 of an empty side. It is still one pass, O(n) time.

How would you find the actual path, not only its length?

Along with best, we remember the node where the best path bends. After the pass, we walk down from that node twice, once into its left subtree and once into its right, each time stepping into the child with the larger height. To make that walk cheap we store each node's height in a map during the pass. Joining the two walks at the bending node gives the path, such as 4 -> 2 -> 1 -> 3.

9Conclusion

We found the diameter of a binary tree, the number of edges on its longest path, with one post-order recursion. Every path bends at one highest node, so each node, once its children have reported their heights, records the path that bends at it, left + right + 2, and returns its own height, 1 + the larger child height. An empty subtree counts as -1, so leaves and single children need no special code. It runs in O(n) time with O(h) stack space and handles trees whose longest path avoids the root. The clue to remember is an answer at a node that combines both subtrees: recurse post-order, return one value up, and record the other.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm that the diameter counts edges and that the path may or may not pass through the root. Every path has one highest node where it bends, and at that node it goes down the deepest branch on each side.

Then, if they want more

So the path bending at a node is its left height plus its right height plus two. A brute force computes those heights with a separate recursion at every node, which is O(n squared) on a chain-shaped tree. Since the answer at a node combines both subtrees, I use one post-order recursion.

My helper returns the height of a node, with minus one for null so a leaf has height zero. After getting both child heights, it updates a best variable with left plus right plus two, and returns one plus the larger child height, because the parent can only extend one branch.

The key point is that I return the height but maximise a different quantity, the bending path. Every node is visited once, so it is O(n) time, and the recursion depth is the tree height, O(h) space, which can be O(n) for a skewed tree, so for very deep trees I would make it iterative. An empty tree and a single node both give zero.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 28 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the diameter of a binary tree, the longest path between any two of its nodes.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-diameter-of-a-binary-tree-the-longest-path-between-any-93930f/