Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Print the level-order traversal of a tree, one list per level. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Print the level-order traversal of a tree, one list per level. 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))
from collections import deque
def levels(root):
    out, q = [], deque([root])
    while q:
        lvl = []
        for _ in range(len(q)):
            n = q.popleft(); lvl.append(n.v)
            if n.l: q.append(n.l)
            if n.r: q.append(n.r)
        out.append(lvl)
    return out
print(levels(build([3, 9, 20, None, None, 15, 7])))
What is printed?
  1. A. [[3], [9, 20, 15, 7]]
  2. B. [[3], [20, 9], [15, 7]]
  3. C. [[3], [9, 20], [15, 7]]
  4. D. [3, 9, 20, 15, 7]

Correct answer: C. [[3], [9, 20], [15, 7]]

BFS with a queue; freezing len(q) at the start of each round separates the levels. O(n) time, O(width) space.

More Coding Interview Problems questions

Exams that ask this topic