Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Delete a node with two children from a BST by replacing it with its inorder successor; print the preorder afterwards.
Problem: Delete a node with two children from a BST by replacing it with its inorder successor; print the preorder afterwards.
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 delete(r, v):
if not r: return r
if v < r.v: r.l = delete(r.l, v)
elif v > r.v: r.r = delete(r.r, v)
else:
if not r.l: return r.r
if not r.r: return r.l
s = r.r
while s.l: s = s.l
r.v = s.v; r.r = delete(r.r, s.v)
return r
root = None
for v in [50, 30, 70, 20, 40, 60, 80, 65]: root = ins(root, v)
root = delete(root, 50)
out = []
def pre(n):
if n: out.append(n.v); pre(n.l); pre(n.r)
pre(root); print(out)What is printed?- A. [60, 30, 20, 40, 70, 65, 80]
- B. [40, 30, 20, 70, 60, 65, 80]
- C. [60, 30, 20, 40, 70, 80]
- D. [65, 30, 20, 40, 70, 60, 80]
Correct answer: A. [60, 30, 20, 40, 70, 65, 80]
50 has two children; its inorder successor is the smallest key in the right subtree, 60. 60 replaces 50, and 60 is deleted from the right subtree, where its right child 65 takes its place under 70. Preorder: 60, 30, 20, 40, 70, 65, 80.
More Coding Interview Problems questions
- Problem: Insert keys into an AVL tree (rebalancing with rotations) and print the root and the tree height (a single node has height 1)…
- Problem: Ackermann's function grows faster than any primitive-recursive function. Compute A(2, 3) and count the recursive calls. python…
- Problem: Count the calls made by naive recursive Fibonacci versus a memoised version for n = 10. python from functools import lrucache…
- What is the time complexity of this loop? python for i in range(1, n + 1): j = 1 while j j <= i: j += 1
- What is the solution of T(n) = 2T(√n) + log n?
- A hash table with separate chaining and simple uniform hashing has n keys in m buckets (load factor α = n/m). What is the expected time of…