Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Trim a BST so that only keys in [lo, hi] remain (keeping BST structure), then print its preorder. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: Trim a BST so that only keys in [lo, hi] remain (keeping BST structure), then print its preorder. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):  # level order, None = missing child
    root = T(xs[0]); q = deque([root]); i = 1
    while i < len(xs):
        node = q.popleft()
        for side in ("l", "r"):
            if i < len(xs) and xs[i] is not None:
                setattr(node, side, T(xs[i])); q.append(getattr(node, side))
            i += 1
    return root
def trim(t, lo, hi):
    if not t: return None
    if t.v < lo: return trim(t.r, lo, hi)
    if t.v > hi: return trim(t.l, lo, hi)
    t.l, t.r = trim(t.l, lo, hi), trim(t.r, lo, hi)
    return t
def pre(t): return [t.v] + pre(t.l) + pre(t.r) if t else []
print(pre(trim(build([8, 3, 12, 1, 6, 10, 14, None, None, 4, 7]), 4, 11)))
What is printed?
  1. A. [6, 4, 7, 8, 10]
  2. B. [8, 6, 4, 7, 10]
  3. C. [8, 3, 6, 4, 7, 10]
  4. D. [8, 6, 4, 7, 10, 12]

Correct answer: B. [8, 6, 4, 7, 10]

If a node is below lo, it and its whole left subtree are out, so the answer is the trimmed right subtree; symmetric for > hi. 3 < 4 is replaced by its trimmed right subtree (6 → 4, 7); 12 > 11 is replaced by its trimmed left subtree (10); 1 and 14 vanish. Preorder 8, 6, 4, 7, 10. O(n).

More Coding Interview Problems questions

Exams that ask this topic