Data Structures & AlgorithmsModerateTCS NQT · Infosys

Problem: A rooted tree has root 1 and children: 1→2 (weight 4), 1→3 (weight 1), 2→4 (weight 2), 2→5 (weight 7), 3→6 (weight 3). The weighted depth of a node is the sum of edge weights from the root. What is the sum of the weighted depths of the leaves (nodes with no children)?

  1. A. 26
  2. B. 21
  3. C. 6
  4. D. 11

Correct answer: B. 21

Leaves 4, 5 and 6 have weighted depths 4 + 2 = 6, 4 + 7 = 11 and 1 + 3 = 4, so the sum is 21. Summing over all non-root nodes adds 4 and 1 (26), using unweighted depths gives 2 + 2 + 2 = 6, and taking only the deepest leaf gives 11.

More Coding Interview Problems questions

Exams that ask this topic