Data Structures & AlgorithmsHardGATE CS · Advanced

A rooted tree has the vertices A–M with root A, given by parents: A is the parent of B, B is the parent of C, B is the parent of D, B is the parent of E, C is the parent of F, F is the parent of G, E is the parent of H, E is the parent of I, I is the parent of J, I is the parent of K, I is the parent of L, I is the parent of M. How many unordered pairs of distinct vertices {u, v} have vertex B as their lowest common ancestor (a vertex may be an ancestor of the other)?

  1. A. 45
  2. B. 84
  3. C. 42
  4. D. 31

Correct answer: C. 42

Let s be the size of the subtree of B and c_i the child subtree sizes. Pairs with LCA B are the pairs that are not both inside one child subtree: C(s,2) - sum C(c_i,2) = 42. Dropping the pairs that include B itself gives 31.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic