DSA interview question
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).
int diameterOfBinaryTree(TreeNode* root); // number of edges
| Input (level order) | Output | Explanation |
|---|---|---|
[1, 2, 3, 4, 5] | 3 | 4-2-1-3 or 5-2-1-3 |
[1, 2, null, 3, 4, 5, null, null, 6] | 4 | 5-3-2-4-6, which avoids the root |
[1, 2] | 1 | |
[1] | 0 | A single node: no edges |
[] | 0 |
(Confirm: the length is counted in edges; the path can start and end anywhere.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in