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?- A. [30, 60, 65, 70, 80] 65 60
- B. [30, 60, 65, 70, 80] 70 60
- C. [30, 65, 60, 70, 80] 60 65
- 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
- Problem: Given the root of a BST with n nodes and a target, return the value closest to the target. What is the best time complexity…
- Problem: Return the maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level…
- Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. Trees are…
- Problem: A trie stores n words of average length L over a 26-letter alphabet. Autocomplete must list whether any word starts with a prefix…
- Problem: Insert words into a trie and count how many stored words start with a given prefix. python def make(words): root = {} for w in…
- Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid. python def islands(g): R, C = len(g)…