Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

What is printed? (diameter of an unweighted tree with two BFS passes)

What is printed? (diameter of an unweighted tree with two BFS passes)
from collections import deque
edges = [(1, 2), (1, 3), (2, 4), (2, 5), (5, 6), (3, 7), (7, 8), (8, 9)]
g = {}
for u, v in edges: g.setdefault(u, []).append(v); g.setdefault(v, []).append(u)
def far(s):
    d = {s: 0}; q = deque([s])
    while q:
        u = q.popleft()
        for v in g[u]:
            if v not in d: d[v] = d[u] + 1; q.append(v)
    x = max(d, key=d.get); return x, d[x]
a, _ = far(1); b2, dia = far(a)
print(a, dia)
  1. A. 9 6
  2. B. 6 7
  3. C. 9 8
  4. D. 9 7

Correct answer: D. 9 7

BFS from any node reaches one end of a diameter (from 1 the farthest node is 9, at depth 4); a second BFS from 9 finds the other end, 6: 9 → 8 → 7 → 3 → 1 → 2 → 5 → 6 = 7 edges. The two-pass trick works for trees (not general graphs). O(n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic