Data Structures & AlgorithmsModerateGATE CS · Codeforces Div 2

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

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

Correct answer: A. 2

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

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic