Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level, counting gaps. 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 maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level, counting gaps. 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 width(root):
    lvl, best = [(root, 0)], 0
    while lvl:
        best = max(best, lvl[-1][1] - lvl[0][1] + 1)
        nxt = []
        for n, i in lvl:
            if n.l: nxt.append((n.l, 2 * i))
            if n.r: nxt.append((n.r, 2 * i + 1))
        lvl = nxt
    return best
print(width(build([1, 3, 2, 5, None, None, 9, 6, None, None, None, None, None, 7])))
What is printed?
  1. A. 4
  2. B. 8
  3. C. 7
  4. D. 2

Correct answer: C. 7

Number positions like a heap (children 2i and 2i + 1) and take last − first + 1 on each level. On the deepest level, 6 (left child of 5) is at position 0 and 7 (left child of 9) is at position 6 → width 7 even though only two nodes exist. Counting nodes per level gives 2. O(n). In C++/Java, re-base indices per level to avoid overflow on deep trees.

More Coding Interview Problems questions

Exams that ask this topic