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?- A. [[1], [3, 2], [4, 5, 6, 7]]
- B. [[1], [2, 3], [7, 6, 5, 4]]
- C. [[1], [3, 2], [7, 6, 5, 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
- Problem: Convert a sorted array into a height-balanced BST and print its preorder. python def pre(a, lo, hi, out): if lo > hi: return out…
- Problem: A tree has n = 10⁵ nodes and arrives as a parent array. You must answer 10⁵ queries 'is u an ancestor of v?'. Which preprocessing…
- Problem: A tree of n nodes is stored as a skewed BST (keys inserted in increasing order). What is the cost of the recursive height…
- Problem: Check whether two trees are mirror images of each other (here: whether a tree is symmetric). Trees are built by build(xs): a…
- Problem: Return the vertical sum of a tree for every column, left to right (root column 0, left child −1, right child +1). Trees are built…
- Problem: Find the minimum depth (nodes on the shortest root-to-LEAF path). The candidate below is buggy. Trees are built by build(xs): a…