PPractick

DSA interview question

Diameter of a Binary Tree

Easy · Data structures · Topics: tree, dfs, recursion

The problem

A network of routers is wired as a binary tree, and the engineers want the worst-case hop count between any two routers: the diameter, the number of edges on the longest path between any two nodes. That path doesn't have to pass through the root. For every node, the longest path that "bends" there is height(left) + height(right) (in edges). So a single post-order pass that computes heights can also track the largest such sum.

Example: [1, 2, 3, 4, 5] → 3 (path 4 → 2 → 1 → 3).

Function signature

int diameterOfBinaryTree(TreeNode* root);  // number of edges

Test cases

Input (level order)OutputExplanation
[1, 2, 3, 4, 5]34-2-1-3 or 5-2-1-3
[1, 2, null, 3, 4, 5, null, null, 6]45-3-2-4-6, which avoids the root
[1, 2]1
[1]0A single node: no edges
[]0

(Confirm: the length is counted in edges; the path can start and end anywhere.)

How interviewers phrase it

Clarifying questions to ask

  1. Edges or nodes? (Edges.)
  2. Must the path go through the root? (No.)
  3. Can the tree be empty? (Return 0.)

Follow-ups to expect

  1. "Why can't you just use the root?"
  2. "What does each node contribute?"
  3. "Why is it O(n)?"
  4. "How would you do it for a general tree or graph?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in