Data Structures & AlgorithmsModerateProduct Company SDE · tree round

Problem: Tree with edges 0-1, 0-2, 1-3, 1-4, 2-5. How many nodes are in the subtree of node 1 (rooted at 0)? Run the DFS code.

Problem: Tree with edges 0-1, 0-2, 1-3, 1-4, 2-5. How many nodes are in the subtree of node 1 (rooted at 0)? Run the DFS code.
import sys
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
g = {i: [] for i in range(6)}
for u, v in edges:
    g[u].append(v)
    g[v].append(u)
def size(u, p):
    s = 1
    for v in g[u]:
        if v != p:
            s += size(v, u)
    return s
print(size(1, 0))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 5
  4. D. 3

Correct answer: D. 3

The subtree of 1 contains 1, 3 and 4. Passing the parent avoids walking back up the tree.

More Coding Interview Problems questions

Exams that ask this topic