Skip to the solution
MediumDSA12 min read

How do you compute the diameter of a binary tree?

751 views

The problem

Question presented to candidate: "Given the root of a binary tree, write a Python function that returns the length of its diameter: the number of edges on the longest path between any two nodes. The path does not have to pass through the root."

What a strong answer should cover:

  • Every path has a highest (bend) node; the longest path bending at a node has height(left) + height(right) edges.
  • The answer is the maximum over all nodes, so a root-only computation is wrong when the longest path sits inside one subtree.
  • One post-order pass: return the height to the parent, record the best left + right on the side โ€” O(n) time, O(h) space.
  • Why recomputing heights at every node is O(n ยท h), O(nยฒ) on a chain.
  • Python details: a nested helper with nonlocal best (or a one-element list) instead of a global, and the 1000-frame recursion limit for deep chains.
  • Edges vs nodes: a single node has diameter 0.

Clarifying questions expected:

  • Is the length measured in edges or in nodes?
  • Must the path go through the root?

Code / implementation expected: Yes โ€” a nested height(node) helper inside diameter(root), in Python 3.

  • trees
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonOne post-order pass: return height, record L + R (5 trees)
PythonReconstruct the longest path; brute force vs one pass

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 68 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you count the number of set bits in an integer?

Continue