Data Structures & AlgorithmsModerateCodeforces Div 2 · ICPC regional

Rooted tree with root 0 and vertices 0 to 8; the edges are 0–1, 1–2, 2–3, 1–4, 1–5, 4–6, 4–7, 6–8 (parent–child). Every edge has length 1. What is the distance between vertices 3 and 5 (number of edges on the path)?

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

Correct answer: D. 3

The path goes up to the lowest common ancestor 1, so the length is 3 + 2 − 2·1 = 3. Adding depths or taking their difference ignores the common ancestor.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic