Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

What is printed? (inorder successor in a BST)

What is printed? (inorder successor in a BST)
def insert(t, k):
    if t is None: return [k, None, None]
    i = 1 if k < t[0] else 2
    t[i] = insert(t[i], k); return t
def pre(t): return [] if t is None else [t[0]] + pre(t[1]) + pre(t[2])
def ino(t): return [] if t is None else ino(t[1]) + [t[0]] + ino(t[2])
def post(t): return [] if t is None else post(t[1]) + post(t[2]) + [t[0]]
def succ(t, k):
    best = None
    while t:
        if k < t[0]: best, t = t[0], t[1]
        else: t = t[2]
    return best
r = None
for k in [20, 8, 22, 4, 12, 10, 14]: r = insert(r, k)
print(succ(r, 8), succ(r, 14), succ(r, 22))
  1. A. 12 20 None
  2. B. 10 22 None
  3. C. 10 20 None
  4. D. 10 20 22

Correct answer: C. 10 20 None

Walk from the root: whenever k is smaller than the node, that node is a candidate and we go left; otherwise go right. 8's successor is the leftmost node of its right subtree (10); 14 has no right subtree, so its successor is the nearest ancestor where we went left (20); 22 is the maximum → None. O(h).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic