Data Structures & AlgorithmsVery hardProduct company OA

In the tree with edges 1–2, 1–3, 2–4, 2–5, 3–6, 5–7, the rerooting technique computes S(v) = sum of distances from v to every other node. What are S(1) and S(5)?

  1. A. S(1) = 11, S(5) = 15
  2. B. S(1) = 10, S(5) = 13
  3. C. S(1) = 11, S(5) = 11
  4. D. S(1) = 11, S(5) = 13

Correct answer: D. S(1) = 11, S(5) = 13

From 1 the distances to 2, 3, 4, 5, 6, 7 are 1, 1, 2, 2, 2, 3 → S(1) = 11. Rerooting: moving the root from parent p to child c gives S(c) = S(p) + n − 2·size(c), with n = 7. size(2) = 4 → S(2) = 11 + 7 − 8 = 10; size(5) = 2 → S(5) = 10 + 7 − 4 = 13. Direct check from 5: 1 + 1 + 2 + 2 + 3 + 4 = 13. Rerooting with + 2·size instead of − gives the wrong values.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic