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?- A. [6, 4, 7, 8, 10]
- B. [8, 6, 4, 7, 10]
- C. [8, 3, 6, 4, 7, 10]
- 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
- Problem: Rebuild a BST from its preorder in O(n) using an upper bound per recursive call, then print its postorder and height (nodes on…
- Problem: Print the top view of a tree (the first node seen in each vertical column, left to right; root column 0, left child −1, right…
- Problem: Return the k-th permutation (1-based, lexicographic) of 1..n directly using the factorial number system. python from math import…
- Problem: Count permutations p of 1..n where for every position i (1-based) p[i] is divisible by i or i is divisible by p[i] (backtracking…
- Problem: Can all matchsticks form a square (every stick used exactly once)? Backtrack placing sticks (longest first) into 4 sides…
- Problem: Insert '+', '−' or '' between the digits (or leave digits joined) so the expression equals the target. Operands may not have…