Data Structures & AlgorithmsVery hardProduct company OA

Problem: Return all node values at exactly distance k from a target node (distance counts edges, moving up or down). Record parent pointers, then BFS from the target. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: Return all node values at exactly distance k from a target node (distance counts edges, moving up or down). Record parent pointers, then BFS from the target. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):  # level order, None = missing child
    root = T(xs[0]); q = deque([root]); i = 1
    while i < len(xs):
        node = q.popleft()
        for side in ("l", "r"):
            if i < len(xs) and xs[i] is not None:
                setattr(node, side, T(xs[i])); q.append(getattr(node, side))
            i += 1
    return root
def dist_k(root, target, k):
    parent = {}; q = deque([root]); start = None
    while q:
        n = q.popleft()
        if n.v == target: start = n
        for c in (n.l, n.r):
            if c: parent[c] = n; q.append(c)
    seen = {start}; frontier = [start]
    for _ in range(k):
        nxt = []
        for n in frontier:
            for m in (n.l, n.r, parent.get(n)):
                if m and m not in seen: seen.add(m); nxt.append(m)
        frontier = nxt
    return sorted(n.v for n in frontier)
print(dist_k(build([1, 2, 3, 4, 5, None, 6, None, None, 7, 8]), 5, 2))
What is printed?
  1. A. [4]
  2. B. [1, 4]
  3. C. [1, 3, 4]
  4. D. [1, 4, 7, 8]

Correct answer: B. [1, 4]

Turning the tree into an undirected graph (children + parent) makes this a plain BFS. Tree: 1 → (2, 3), 2 → (4, 5), 3 → (–, 6), 5 → (7, 8). From 5: distance 1 = {2, 7, 8}; distance 2 = {1, 4} (7 and 8 are leaves). Searching only downwards would find nothing at depth 2; 3 is at distance 3. O(n).

More Coding Interview Problems questions

Exams that ask this topic