Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Return the zigzag level order (left→right, then right→left, alternating). 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 zigzag level order (left→right, then right→left, alternating). 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 zig(root):
    out, lvl, flip = [], [root], False
    while lvl:
        vals = [n.v for n in lvl]
        out.append(vals[::-1] if flip else vals)
        lvl = [c for n in lvl for c in (n.l, n.r) if c]
        flip = not flip
    return out
print(zig(build([1, 2, 3, 4, 5, 6, 7])))
What is printed?
  1. A. [[1], [3, 2], [4, 5, 6, 7]]
  2. B. [[1], [2, 3], [7, 6, 5, 4]]
  3. C. [[1], [3, 2], [7, 6, 5, 4]]
  4. D. [[1], [2, 3], [4, 5, 6, 7]]

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

Collect each level left to right and reverse every second one: level 1 is reversed to [3, 2], level 2 is printed normally. Reversing the child-collection order itself instead of the printed values is a common source of scrambled output. O(n).

More Coding Interview Problems questions

Exams that ask this topic