Data Structures & AlgorithmsHardTCS NQT Digital · Product Company SDE

Problem: A rooted tree (root 1) has parent pointers: 2→1, 3→1, 4→2, 5→2, 6→4, 7→6, 8→3, 9→8. How many nodes lie on the path between node 7 and node 9 (both endpoints included)?

  1. A. 7
  2. B. 9
  3. C. 4
  4. D. 8

Correct answer: D. 8

The LCA of 7 and 9 is the root 1, so the path is 7-6-4-2-1-3-8-9: depth(7) + depth(9) − 2·depth(LCA) = 4 + 3 − 0 = 7 edges, hence 8 nodes. Reporting edges gives 7, counting every node in the tree gives 9, and 4 is just the depth of node 7.

More Coding Interview Problems questions

Exams that ask this topic