Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs.

Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs.
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def ins(r, v):
    if not r: return T(v)
    if v < r.v: r.l = ins(r.l, v)
    else: r.r = ins(r.r, v)
    return r
def lca(r, a, b):
    while r:
        if a < r.v and b < r.v: r = r.l
        elif a > r.v and b > r.v: r = r.r
        else: return r.v
root = None
for v in [20, 8, 22, 4, 12, 10, 14]: root = ins(root, v)
print(lca(root, 10, 22), lca(root, 10, 14), lca(root, 4, 14))
What is printed?
  1. A. 20 10 8
  2. B. 8 12 8
  3. C. 20 12 4
  4. D. 20 12 8

Correct answer: D. 20 12 8

In a BST the LCA is the first node whose value lies between the two keys (inclusive). 10 and 22 split at the root 20; 10 and 14 split at 12; 4 and 14 split at 8.

More Coding Interview Problems questions

Exams that ask this topic