Diameter of Binary Tree solution explained

The Diameter of Binary Tree solution is one depth-first pass: each call returns the height of its subtree, and on the way back up it checks whether the left height plus the right height beats the longest path found so far. That sum is the longest path that bends at the current node, and the best of those across all nodes is the diameter, in O(n) time.

By Published 7 min read

What is being measured

You get the root of a binary tree. A path is any sequence of nodes connected by edges, with no node visited twice. Its length is the number of edges it uses. Return the length of the longest path anywhere in the tree. The two ends can be any nodes, and the path may or may not pass through the root.

        1
       /
      2
     / \
    3   4
   /     \
  5       6
A tree drawn for this page. The answer is 4, along 5-3-2-4-6, which never touches the root.

Through the root, the best you can do is 1 down to 5 or 6, which is 3 edges. The longest path instead bends at node 2. A tree with a root and two leaves has diameter 2. A single node has diameter 0, and so does an empty tree. Some versions count nodes instead of edges, which adds one, so confirm the unit before you code.

What interviewers look for

Diameter is a favorite early tree question because it separates candidates who know the shape of recursive tree code from those who are still guessing. The interviewer wants to see you notice that the answer is not simply "height of left plus height of right at the root", and then fold the per-node check into the height computation so the tree is walked once. Explaining why the function returns one thing but tracks another is the main thing to get right out loud.

The idea: every path bends somewhere

Look at any path in a tree and find its highest node. The path climbs up to that node from one side and goes down the other, or it starts at that node and goes down one side. Either way, the longest path bending at a node uses the deepest route into its left subtree and the deepest route into its right subtree. If height counts edges plus one per level, that length is simply height(left) + height(right). So the diameter is the largest such sum over all nodes.

Slow version: recompute heights at each node

Turning that idea directly into code gives a function that, at each node, calls a separate height function on both children and then recurses into both children to check their own bends. On a balanced tree that is O(n log n), but on a tree shaped like a long chain the height calls repeat almost the whole tree at every level, so the worst case is O(n²).

def height(node):
    if node is None:
        return 0
    return 1 + max(height(node.left), height(node.right))

def widest_path_slow(root):
    if root is None:
        return 0
    through_here = height(root.left) + height(root.right)
    return max(through_here, widest_path_slow(root.left), widest_path_slow(root.right))
Separate height calls at every node: O(n²) on a chain. Nodes have val, left and right.

One pass: return the height, record the bend

The slow version computes heights bottom-up again and again. A post-order traversal already visits each node after both of its children, which is exactly when both child heights are known. So write a single helper that returns the height of its subtree, and before it returns, compare left + right with the best path seen so far. The function's return value serves the parent; the side variable serves the final answer.

def widest_path(root):
    best = 0

    def depth(node):
        nonlocal best
        if node is None:
            return 0
        left = depth(node.left)
        right = depth(node.right)
        best = max(best, left + right)  # edges on the path bending here
        return 1 + max(left, right)

    depth(root)
    return best
Python: post-order helper with a nonlocal best. O(n) time, O(h) stack.
function widestPath(root) {
  let best = 0;
  const depth = (node) => {
    if (node === null) return 0;
    const left = depth(node.left);
    const right = depth(node.right);
    best = Math.max(best, left + right);
    return 1 + Math.max(left, right);
  };
  depth(root);
  return best;
}
JavaScript: the same helper as a closure. Nodes have val, left and right, with null for a missing child.

Trace the drawing. Leaves 5 and 6 return 1. Node 3 sees 1 and 0, records 1, returns 2. Node 4 sees 0 and 1, records 1, returns 2. Node 2 sees 2 and 2, records 4, returns 3. The root sees 3 and 0, which is only 3, so the best stays 4.

If you would rather not use a side variable

Some interviewers ask for a pure function. Return a pair instead: the subtree's height and the best path found inside it. The parent combines them as max(left best, right best, left height + right height). Same complexity, a little more typing, and no shared state.

Complexity

n nodes, height h
ApproachTimeExtra space
Height calls at every nodeO(n²) worst, O(n log n) balancedO(h) recursion
Single post-order passO(n)O(h) recursion
Post-order with an explicit stackO(n)O(n) for the stack and stored heights
n nodes, height h. Scroll sideways on a small screen.

The recursion depth equals the tree height, which can be n for a chain. Python's default recursion limit is around a thousand frames, so a very deep tree needs either a higher limit or an iterative post-order traversal that stores each node's height in a dictionary.

Edge cases

  • Empty tree: 0.
  • Single node: 0, since there are no edges.
  • A chain leaning one way: the diameter is the number of nodes minus one, and it bends at the top.
  • A long path entirely inside one subtree, like the drawing above.
  • A perfectly balanced tree, where the diameter passes through the root.

Typical errors

  • Returning left + right from the helper. The parent needs a height, not a bent path, since a path cannot bend twice.
  • Only checking the root, which fails on the drawing above.
  • Mixing node counts and edge counts, which gives off-by-one answers.
  • Initializing best inside the helper so it resets on every call.

Follow-ups

  • Return the path itself. Have the helper return the deepest leaf along with the height, and record both ends when the best improves.
  • Weighted edges. Return the heaviest downward path instead of a height; the combination rule is unchanged.
  • Maximum path sum with node values. The same shape with sums, where negative branches are dropped by taking max(0, child).
  • A general tree or graph with no cycles. Run breadth-first search from any node to find the farthest node, then search again from that node. The second distance is the diameter.

Talking it through

Fictional example

How a candidate might explain it
Candidate
Every path has a highest node where it bends. At that node its length is the left height plus the right height, so the diameter is the biggest such sum.
Candidate
I'll write one post-order helper that returns the height. Before returning, it updates a best variable with left plus right.
Candidate
The return value has to be a height because a parent can only extend one side of a path. That's one pass, O(n), with stack depth equal to the height.

More tree problems

Balanced Binary Tree uses the same return-a-height helper with an early exit. Count Good Nodes in Binary Tree passes information down instead of up, and Binary Tree Level Order Traversal covers the breadth-first side. All are on the coding problems hub.

Practicing with Natively

Tree prompts usually come with a drawing, so a screenshot is the natural way in. During practice on Mac or Windows, Natively can read the tree from your screen, point out that the longest path may skip the root, and help you phrase why the helper returns a height. The transcript of your mock is saved, so you can check later whether you said it clearly. More on the AI assistant for coding interviews.

Questions people ask

How do you find the diameter of a binary tree?

Run one depth-first pass where each call returns its subtree's height. At every node, compare the left height plus the right height with the best seen so far. The largest sum is the diameter, found in O(n) time.

Does the diameter of a binary tree always pass through the root?

No. The longest path can bend at any node, for example deep inside a left subtree when the root has a short right side. That is why every node is checked, not only the root.

Is the diameter measured in nodes or edges?

The common version counts edges, so a single node has diameter 0. Some versions count nodes, which is one more. Ask the interviewer which one they want.

What is the time complexity of Diameter of Binary Tree?

O(n) for the single post-order pass, with O(h) recursion depth where h is the tree height. Calling a separate height function at every node is O(n squared) on a chain-shaped tree.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP