Data Structures & AlgorithmsModerateICPC regional · GATE CS top band

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

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

Correct answer: C. 4

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

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic