Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Print the top view of a tree (the first node seen in each vertical column, left to right; root column 0, left child −1, right child +1). BFS guarantees the shallowest node per column. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: Print the top view of a tree (the first node seen in each vertical column, left to right; root column 0, left child −1, right child +1). BFS guarantees the shallowest node per column. 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 top_view(root):
    first = {}; q = deque([(root, 0)])
    while q:
        n, c = q.popleft()
        if c not in first: first[c] = n.v
        if n.l: q.append((n.l, c - 1))
        if n.r: q.append((n.r, c + 1))
    return [first[c] for c in sorted(first)]
print(top_view(build([1, 2, 3, None, 4, 5, 6, None, 8, 7])))
What is printed?
  1. A. [2, 1, 3, 6]
  2. B. [2, 1, 8, 6]
  3. C. [7, 2, 1, 3, 6]
  4. D. [2, 4, 1, 3, 6]

Correct answer: A. [2, 1, 3, 6]

Columns: 1 (0), 2 (−1), 3 (+1), 4 (0), 5 (0), 6 (+2), 8 (+1), 7 (−1). BFS reaches each column's shallowest node first: −1 → 2, 0 → 1, +1 → 3, +2 → 6. A preorder DFS that keeps the first node visited reaches 8 (depth 3, via 2 → 4 → 8) before 3 (depth 1) and wrongly reports 8 for column +1. O(n log n) with the final sort.

More Coding Interview Problems questions

Exams that ask this topic