GATE DA 2024, Q.38: Output of a recursive count over a dict tree
The question
def count(child_dict, i): if i is not a key, return 1; otherwise ans = 1 and add count(child_dict, j) for each child j, then return ans. With child_dict[0] = [1, 2], child_dict[1] = [3, 4, 5], child_dict[2] = [6, 7, 8], what does print(count(child_dict, 0)) show?
def count(child_dict, i):
if i not in child_dict.keys():
return 1
ans = 1
for j in child_dict[i]:
ans += count(child_dict, j)
return ans
child_dict = dict()
child_dict[0] = [1, 2]
child_dict[1] = [3, 4, 5]
child_dict[2] = [6, 7, 8]
print(count(child_dict, 0))- (A) 6
- (B) 1
- (C) 8
- (D) 9
Solve it step by step
- Draw the tree. 0 has children 1 and 2; 1 has 3, 4, 5; 2 has 6, 7, 8.
- Leaves. 3 to 8 are not keys, so each returns 1.
- Middle nodes. Nodes 1 and 2 each return 1 + 1 + 1 + 1 = 4.
- Root. count(0) = 1 + 4 + 4 = 9.
Answer: (D) 9
Official IISc Bengaluru answer key: D.
Common mistake. Counting only the leaves (6) or forgetting the root (8). Every call starts with ans = 1, so every node counts once.
Remember. A recursion that starts at 1 and adds each child returns the size of the subtree.
Want every question solved? The past-paper pack has all 195 questions from 2024, 2025 and 2026 for ₹499. The cheat sheet pack has 23 printable sheets for ₹399.
See the past-paper pack See the cheat sheetsSource: official GATE DA 2024 question paper and answer key (IISc Bengaluru). The question is lightly reworded; every number and option is kept.