Data Structures & AlgorithmsModerateWipro · Accenture pattern

What is printed? (count leaves, internal nodes and full nodes of a binary tree)

What is printed? (count leaves, internal nodes and full nodes of a binary tree)
T = {1: (2, 3), 2: (4, None), 3: (5, 6), 4: (None, 7), 5: (None, None), 6: (None, None), 7: (None, None)}
leaves = sum(1 for v, (l, r) in T.items() if l is None and r is None)
full = sum(1 for v, (l, r) in T.items() if l and r)
print(leaves, len(T) - leaves, full)
  1. A. 3 4 3
  2. B. 3 4 2
  3. C. 4 3 2
  4. D. 3 4 1

Correct answer: B. 3 4 2

Leaves 5, 6, 7; internal 1, 2, 3, 4; nodes with two children are 1 and 3. For any binary tree, leaves = full nodes + 1 (3 = 2 + 1), regardless of nodes with one child.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic