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)
  1. A. [25, 20, 10, 22, 40, 30, 50, 45] ['LL', 'LR', 'RR', 'RR'] 3
  2. B. [20, 10, 30, 25, 22, 40, 50, 45] ['LL', 'LR', 'RL'] 4
  3. C. [25, 20, 10, 22, 45, 40, 30, 50] ['LL', 'RL', 'LR', 'RR'] 3
  4. 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.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic