Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

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: Insert keys into an AVL tree (rebalancing with rotations) and print the root and the tree height (a single node has height 1).
class T:
    def __init__(s, v): s.v, s.l, s.r, s.h = v, None, None, 1
def h(n): return n.h if n else 0
def fix(n): n.h = 1 + max(h(n.l), h(n.r)); return n
def rot_r(y): x = y.l; y.l = x.r; x.r = y; fix(y); return fix(x)
def rot_l(x): y = x.r; x.r = y.l; y.l = x; fix(x); return fix(y)
def ins(n, v):
    if not n: return T(v)
    if v < n.v: n.l = ins(n.l, v)
    else: n.r = ins(n.r, v)
    fix(n); b = h(n.l) - h(n.r)
    if b > 1 and v < n.l.v: return rot_r(n)
    if b < -1 and v >= n.r.v: return rot_l(n)
    if b > 1: n.l = rot_l(n.l); return rot_r(n)
    if b < -1: n.r = rot_r(n.r); return rot_l(n)
    return n
root = None
for v in [10, 20, 30, 40, 50, 25]: root = ins(root, v)
print(root.v, root.h)
What is printed?
  1. A. 20 3
  2. B. 30 3
  3. C. 40 3
  4. D. 10 6

Correct answer: B. 30 3

10, 20, 30 trigger a left rotation (root 20); 40, 50 rotate 30–40–50 into 40 with children 30, 50. Inserting 25 (under 30) makes the root's right subtree height 3 against a left height of 1, a right-left case, so a double rotation makes 30 the root (children 20 and 40) with height 3.

More Coding Interview Problems questions

Exams that ask this topic