Data Structures & AlgorithmsVery hardProduct company OA
AVL insertions (rotations labelled by imbalance case). What is printed (preorder, rotation cases in order, height in edges)?
AVL insertions (rotations labelled by imbalance case). What is printed (preorder, rotation cases in order, height in edges)?
class N:
def __init__(s, k): s.k, s.l, s.r, s.h = k, None, None, 1
h = lambda n: n.h if n else 0
rot = []
def upd(n): n.h = 1 + max(h(n.l), h(n.r))
def rr(y):
x = y.l; y.l = x.r; x.r = y; upd(y); upd(x); return x
def rl(x):
y = x.r; x.r = y.l; y.l = x; upd(x); upd(y); return y
def ins(n, k):
if not n: return N(k)
if k < n.k: n.l = ins(n.l, k)
else: n.r = ins(n.r, k)
upd(n); b = h(n.l) - h(n.r)
if b > 1 and k < n.l.k: rot.append("LL"); return rr(n)
if b < -1 and k > n.r.k: rot.append("RR"); return rl(n)
if b > 1: rot.append("LR"); n.l = rl(n.l); return rr(n)
if b < -1: rot.append("RL"); n.r = rr(n.r); return rl(n)
return n
def pre(n): return [n.k] + pre(n.l) + pre(n.r) if n else []
root = None
for k in [40, 20, 10, 25, 30, 22, 50, 45]: root = ins(root, k)
print(pre(root), rot, h(root) - 1)- A. [25, 20, 10, 22, 40, 30, 50, 45] ['LL', 'LR', 'RR', 'RR'] 3
- B. [20, 10, 30, 25, 22, 40, 50, 45] ['LL', 'LR', 'RL'] 4
- C. [25, 20, 10, 22, 45, 40, 30, 50] ['LL', 'RL', 'LR', 'RR'] 3
- D. [25, 20, 10, 22, 40, 30, 50, 45] ['LL', 'LR', 'RL', 'RR'] 3
Correct answer: D. [25, 20, 10, 22, 40, 30, 50, 45] ['LL', 'LR', 'RL', 'RR'] 3
40, 20, 10: LL at 40 → 20(10, 40). 25 then 30 make 40 left-heavy with the new key in its left child's RIGHT subtree → LR → 30(25, 40). 22 lands under 25 and makes 20 right-heavy with the key in the right child's LEFT subtree → RL, root becomes 25(20(10, 22), 30(–, 40)). 50 makes 30 right-right heavy → RR → 40(30, 50). 45 goes under 50 without violating balance. Final height 3. Picking the case from the root's balance alone, instead of where the key went, mislabels LR/RL.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- B-tree with minimum degree t = 2 (a 2-3-4 tree, at most 3 keys per node) using the single-pass insertion that splits every FULL node on…
- Building a min-heap from [9, 8, 7, 6, 5, 4, 3]: (a) seven sift-up insertions, (b) bottom-up heapify. What is printed (heaps and swap…
- Exact count of the innermost statement for n = 30 (j advances by i, k advances by j). What is printed? python c = 0 n = 30 for i in…
- A memoised recursion f(n) = f(n//2) + f(n//3) + f(n//6) is evaluated for n = 10¹². How many distinct calls (cache misses) are made? python…
- Patience-sorting tails array for the longest STRICTLY increasing subsequence, and the length for the non-decreasing variant. What is…
- Weighted interval scheduling (start, end, value): DP over jobs sorted by end time with binary search for the last compatible job, versus…