Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Zigzag level-order traversal (left to right, then right to left, alternating).

Problem: Zigzag level-order traversal (left to right, then right to left, alternating).
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
    nodes = [T(x) if x is not None else None for x in xs]
    kids = iter(nodes[1:])
    for nd in nodes:
        if nd:
            nd.l = next(kids, None); nd.r = next(kids, None)
    return nodes[0]
from collections import deque
def zigzag(root):
    out, q, ltr = [], deque([root]), True
    while q:
        lvl = [q.popleft() for _ in range(len(q))]
        vals = [n.v for n in lvl]
        out.append(vals if ltr else vals[::-1]); ltr = not ltr
        for n in lvl:
            if n.l: q.append(n.l)
            if n.r: q.append(n.r)
    return out
print(zigzag(build([1, 2, 3, 4, 5, 6, 7, 8])))
What is printed?
  1. A. [[1], [3, 2], [7, 6, 5, 4], [8]]
  2. B. [[1], [2, 3], [4, 5, 6, 7], [8]]
  3. C. [[1], [3, 2], [4, 5, 6, 7], [8]]
  4. D. [[1], [3, 2], [4, 5, 6, 7], [9]]

Correct answer: C. [[1], [3, 2], [4, 5, 6, 7], [8]]

Levels are [1], [2, 3], [4, 5, 6, 7], [8]; reversing every second level gives [1], [3, 2], [4, 5, 6, 7], [8]. The single-node last level looks the same in either direction.

More Coding Interview Problems questions

Exams that ask this topic