Data Structures & AlgorithmsVery hardProduct company OA

What is the diameter (largest distance between any two nodes) of the weighted tree with edges 1–2 (3), 1–3 (4), 2–4 (2), 2–5 (6), 3–6 (5), 6–7 (1)? (Two DFS passes: farthest from any node, then farthest from that.)

  1. A. 16
  2. B. 19
  3. C. 13
  4. D. 21

Correct answer: B. 19

From 1 the distances are 2: 3, 3: 4, 4: 5, 5: 9, 6: 9, 7: 10, so the first pass ends at 7. From 7 the farthest node is 5: 7–6–3–1–2–5 = 1 + 5 + 4 + 3 + 6 = 19, the diameter. Stopping after the first pass reports only 10; the path with the most edges is not automatically the heaviest one.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic