Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: A tree has 8 nodes 0–7 and edges: 0–1, 1–2, 1–3, 3–4, 4–5, 3–6, 6–7. What is the diameter of the tree, measured as the number of edges on the longest simple path?

  1. A. 5
  2. B. 3
  3. C. 6
  4. D. 4

Correct answer: D. 4

Two BFS passes: the farthest node from any start is an endpoint of a diameter, and the second BFS from it gives the length. Paths 0-1-3-4-5 and 2-1-3-6-7 both have 4 edges, the longest possible here.

More Coding Interview Problems questions

Exams that ask this topic