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

Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. 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 flatten(t):
    cur = t
    while cur:
        if cur.l:
            p = cur.l
            while p.r: p = p.r
            p.r, cur.r, cur.l = cur.r, cur.l, None
        cur = cur.r
r = build([1, 2, 5, 3, 4, None, 6])
flatten(r)
out = []
while r: out.append(r.v); r = r.r
print(out)
What is printed?
  1. A. [1, 2, 3, 4, 5, 6]
  2. B. [3, 2, 4, 1, 5, 6]
  3. C. [1, 2, 5, 3, 4, 6]
  4. D. [1, 5, 6, 2, 3, 4]

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

Morris-style: hang the right subtree after the rightmost node of the left subtree, move the left subtree to the right, and continue. The result follows preorder 1, 2, 3, 4, 5, 6 in O(n) time and O(1) extra space. [1, 2, 5, 3, 4, 6] is the level order.

More Coding Interview Problems questions

Exams that ask this topic