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

Problem: Return the right-side view of a tree (the last node of each level). Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Return the right-side view of a tree (the last node of each level). Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
    def __init__(self, v, l=None, r=None):
        self.v, self.l, self.r = v, l, r
def build(xs, i=0):
    if i >= len(xs) or xs[i] is None: return None
    return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def right_view(t, d=0, out=None):
    if out is None: out = []
    if not t: return out
    if d == len(out): out.append(t.v)
    right_view(t.r, d + 1, out)
    right_view(t.l, d + 1, out)
    return out
print(right_view(build([1, 2, 3, 4, None, None, None, 8])))
What is printed?
  1. A. [1, 3, 4, 8]
  2. B. [1, 3]
  3. C. [1, 3, 8]
  4. D. [1, 2, 4, 8]

Correct answer: A. [1, 3, 4, 8]

DFS visiting right before left records the first node seen at each depth. Depth 2 has only 4 (under 2) and depth 3 only 8, so they are visible from the right even though they hang on the left. Returning only the rightmost spine (1, 3) is the classic mistake. O(n).

More Coding Interview Problems questions

Exams that ask this topic