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?- A. [[1], [3, 2], [7, 6, 5, 4], [8]]
- B. [[1], [2, 3], [4, 5, 6, 7], [8]]
- C. [[1], [3, 2], [4, 5, 6, 7], [8]]
- 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
- Find the bug: this BST validator compares each node only with its own children. python class T: def init(s, v): s.v, s.l, s.r = v, None…
- A binary tree with 12 nodes is serialised in preorder, writing '#' for every missing child. How many '#' markers appear?
- Problem: Return the diameter of a binary tree (number of EDGES on the longest path between any two nodes). python class T: def init(s, v)…
- Problem: A node of a directed graph is 'safe' if every path from it ends at a terminal node (no outgoing edges). List the safe nodes…
- Problem: Find the bridges and articulation points of an undirected graph using DFS discovery times and low-links. python import sys…
- Problem: Count the strongly connected components and the number of edges in the condensation DAG (Kosaraju). python n = 8 E =…