Data Structures & AlgorithmsModerateTCS NQT · tree warm-up

Problem: Count the nodes at depth exactly 2 in the rooted tree with children 0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []. Root 0 has depth 0. Run the code.

Problem: Count the nodes at depth exactly 2 in the rooted tree with children 0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []. Root 0 has depth 0. Run the code.
ch = {0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []}
cur = [0]
for _ in range(2):
    cur = [v for u in cur for v in ch[u]]
print(len(cur))
What is printed?
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 5

Correct answer: A. 3

The depth-2 nodes are the children of 1 and 2, namely 3, 4 and 5, so the answer is 3. Counting the root's children (2) is the trap.

More Coding Interview Problems questions

Exams that ask this topic