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?- A. [1, 3, 4, 8]
- B. [1, 3]
- C. [1, 3, 8]
- 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
- Problem: Check whether a binary tree is a valid BST. The candidate solution compares each node only with its children. Trees are built by…
- Problem: Find the lowest common ancestor of two keys in a BST. Trees are built by build(xs): a level-order list where index i has children…
- Problem: Find the k-th smallest key in a BST. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2…
- Problem: Return the diameter of a tree – the number of edges on the longest path between any two nodes. Trees are built by build(xs): a…
- Problem: Find the maximum sum of any path in a tree (a path goes between any two nodes, need not pass through the root, values may be…
- Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has…