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

Problem: Delete key 50 (a node with two children) from the BST built by inserting 50, 30, 70, 60, 80, 65 – replacing it with its inorder successor – and print the inorder and the new root.

Problem: Delete key 50 (a node with two children) from the BST built by inserting 50, 30, 70, 60, 80, 65 – replacing it with its inorder successor – and print the inorder and the new root.
def ins(t, k):
    if t is None: return {'k': k, 'l': None, 'r': None}
    side = 'l' if k < t['k'] else 'r'
    t[side] = ins(t[side], k); return t
def delete(t, k):
    if t is None: return None
    if k < t['k']: t['l'] = delete(t['l'], k)
    elif k > t['k']: t['r'] = delete(t['r'], k)
    else:
        if not t['l']: return t['r']
        if not t['r']: return t['l']
        s = t['r']
        while s['l']: s = s['l']
        t['k'] = s['k']
        t['r'] = delete(t['r'], s['k'])
    return t
def ino(t): return [] if t is None else ino(t['l']) + [t['k']] + ino(t['r'])
r = None
for k in [50, 30, 70, 60, 80, 65]: r = ins(r, k)
r = delete(r, 50)
print(ino(r), r['k'], r['r']['l']['k'])
What is printed?
  1. A. [30, 60, 65, 70, 80] 65 60
  2. B. [30, 60, 65, 70, 80] 70 60
  3. C. [30, 65, 60, 70, 80] 60 65
  4. D. [30, 60, 65, 70, 80] 60 65

Correct answer: D. [30, 60, 65, 70, 80] 60 65

The inorder successor of 50 is the leftmost node of its right subtree: 60. 60's key is copied into the root, then 60 is deleted from the right subtree; it has a right child 65, which takes its place under 70. Inorder stays sorted. O(h).

More Coding Interview Problems questions

Exams that ask this topic