Data Structures & AlgorithmsModerateTCS NQT · Product Company SDE

Problem: A tree on 5 nodes is given by edges 1-2, 2-3, 2-4, 4-5. The diameter (in edges) of this tree is what value?

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

Correct answer: A. 3

Two BFS passes: the farthest node from 1 is 5 (distance 3), and the farthest from 5 is 3 at distance 3 as well, so the diameter is three edges.

More Coding Interview Problems questions

Exams that ask this topic