MODULE 6.5: AVL TREES — SELF-BALANCING & ROTATIONS

Master height-balanced Binary Search Trees—Balance Factor (BF ∈ {-1, 0, +1}), LL, RR, LR, and RL rotations, and guaranteed $O(\log n)$ worst-case search even on sorted inputs.

💡 Summary: Preventing Skewed BST Degeneration Automatically

A plain Binary Search Tree can degrade into a degenerate linked list of height $O(n)$ when keys are inserted in sorted or reverse-sorted order, turning $O(\log n)$ lookup into slow $O(n)$ scans. An AVL Tree (named after Adelson-Velsky and Landis) is a self-balancing BST that enforces a strict height invariant at every node: the Balance Factor (BF = height(left) - height(right)) must always be -1, 0, or +1.

Whenever an insertion or deletion pushes a node's balance factor outside [-1, +1], the AVL tree restores balance in $O(1)$ pointer rewiring using single (LL, RR) or double (LR, RL) rotations—guaranteeing height $h \le 1.44 \log_2(n + 2) = O(\log n)$ in all cases.

1. Balance Factor & Four Rebalancing Rotations (LL, RR, LR, RL)
When a node becomes unbalanced after an update, inspect its balance factor and child skew to pick the matching rotation:
  • Left-Left (LL Case, BF > +1 and key in left-left): Fix with a single Right Rotation.
  • Right-Right (RR Case, BF < -1 and key in right-right): Fix with a single Left Rotation.
  • Left-Right (LR Case, BF > +1 and key in left-right): Fix with a Left Rotation on the left child followed by a Right Rotation on the node.
  • Right-Left (RL Case, BF < -1 and key in right-left): Fix with a Right Rotation on the right child followed by a Left Rotation on the node.
Metric / Operation Unbalanced BST (Worst Case) AVL Tree (Guaranteed) Notes
Tree Height ($h$) $O(n)$ $O(\log n)$ ($\le 1.44\log_2(n+2)$) Strict balance factor in $\{-1, 0, +1\}$
search(key) $O(n)$ $O(\log n)$ Faster read lookup than Red-Black trees
insert(key) / delete(key) $O(n)$ $O(\log n)$ At most 1 rotation on insert; up to $O(\log n)$ on delete
Python (avl_tree_rotations.py)
class AVLNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.height = 1  # Height in nodes (leaf = 1)

def get_height(node):
    return node.height if node else 0

def get_balance(node):
    return (get_height(node.left) - get_height(node.right)) if node else 0

def update_height(node):
    node.height = 1 + max(get_height(node.left), get_height(node.right))

def right_rotate(y):
    x = y.left
    t2 = x.right
    x.right = y
    y.left = t2
    update_height(y)
    update_height(x)
    return x

def left_rotate(x):
    y = x.right
    t2 = y.left
    y.left = x
    x.right = t2
    update_height(x)
    update_height(y)
    return y

def avl_insert(node, key):
    if not node:
        return AVLNode(key)
    if key < node.key:
        node.left = avl_insert(node.left, key)
    elif key > node.key:
        node.right = avl_insert(node.right, key)
    else:
        return node

    update_height(node)
    bf = get_balance(node)

    # LL Case
    if bf > 1 and key < node.left.key:
        return right_rotate(node)
    # RR Case
    if bf < -1 and key > node.right.key:
        return left_rotate(node)
    # LR Case
    if bf > 1 and key > node.left.key:
        node.left = left_rotate(node.left)
        return right_rotate(node)
    # RL Case
    if bf < -1 and key < node.right.key:
        node.right = right_rotate(node.right)
        return left_rotate(node)

    return node

def preorder_with_bf(node):
    if not node:
        return []
    return [f"{node.key}(bf={get_balance(node)})"] + preorder_with_bf(node.left) + preorder_with_bf(node.right)

root = None
for val in [10, 20, 30, 40, 50, 25]:  # Monotonic/skewed-prone sequence
    root = avl_insert(root, val)

print("AVL Root Key   :", root.key)
print("Preorder + BF  :", " -> ".join(preorder_with_bf(root)))
Output: AVL Root Key : 30 Preorder + BF : 30(bf=0) -> 20(bf=0) -> 10(bf=0) -> 25(bf=0) -> 40(bf=-1) -> 50(bf=0)
2. AVL Deletion & Height Guarantee Comparison
Two key points distinguish AVL deletion and tree-balancing behavior:
  • AVL Deletion Rebalancing: After removing a node using standard BST deletion, walk back up to the root updating heights and applying LL/RR/LR/RL rotations whenever |BF| > 1 (unlike insertion, a single deletion may trigger rotations at multiple ancestor levels).
  • Read-Heavy vs. Write-Heavy Balance: AVL trees stay slightly more strictly balanced than Red-Black trees, giving marginally faster lookups at the cost of slightly more rotations during frequent updates.
C++ (avl_delete_and_search.cpp)
#include 
#include 
using namespace std;

struct Node {
    int key, height;
    Node *left, *right;
    Node(int k) : key(k), height(1), left(nullptr), right(nullptr) {}
};

int h(Node* n) { return n ? n->height : 0; }
int bf(Node* n) { return n ? h(n->left) - h(n->right) : 0; }

Node* rightRotate(Node* y) {
    Node* x = y->left;
    Node* t2 = x->right;
    x->right = y;
    y->left = t2;
    y->height = 1 + max(h(y->left), h(y->right));
    x->height = 1 + max(h(x->left), h(x->right));
    return x;
}

Node* leftRotate(Node* x) {
    Node* y = x->right;
    Node* t2 = y->left;
    y->left = x;
    x->right = t2;
    x->height = 1 + max(h(x->left), h(x->right));
    y->height = 1 + max(h(y->left), h(y->right));
    return y;
}

Node* minNode(Node* n) {
    while (n && n->left) n = n->left;
    return n;
}

Node* insertAVL(Node* root, int key) {
    if (!root) return new Node(key);
    if (key < root->key) root->left = insertAVL(root->left, key);
    else if (key > root->key) root->right = insertAVL(root->right, key);
    else return root;

    root->height = 1 + max(h(root->left), h(root->right));
    int balance = bf(root);

    if (balance > 1 && key < root->left->key) return rightRotate(root);
    if (balance < -1 && key > root->right->key) return leftRotate(root);
    if (balance > 1 && key > root->left->key) {
        root->left = leftRotate(root->left);
        return rightRotate(root);
    }
    if (balance < -1 && key < root->right->key) {
        root->right = rightRotate(root->right);
        return leftRotate(root);
    }
    return root;
}

Node* deleteAVL(Node* root, int key) {
    if (!root) return nullptr;
    if (key < root->key) root->left = deleteAVL(root->left, key);
    else if (key > root->key) root->right = deleteAVL(root->right, key);
    else {
        if (!root->left || !root->right) {
            Node* temp = root->left ? root->left : root->right;
            delete root;
            return temp;
        }
        Node* succ = minNode(root->right);
        root->key = succ->key;
        root->right = deleteAVL(root->right, succ->key);
    }

    if (!root) return nullptr;
    root->height = 1 + max(h(root->left), h(root->right));
    int balance = bf(root);

    if (balance > 1 && bf(root->left) >= 0) return rightRotate(root);
    if (balance > 1 && bf(root->left) < 0) {
        root->left = leftRotate(root->left);
        return rightRotate(root);
    }
    if (balance < -1 && bf(root->right) <= 0) return leftRotate(root);
    if (balance < -1 && bf(root->right) > 0) {
        root->right = rightRotate(root->right);
        return leftRotate(root);
    }
    return root;
}

void inorder(Node* root) {
    if (!root) return;
    inorder(root->left);
    cout << root->key << " ";
    inorder(root->right);
}

int main() {
    Node* root = nullptr;
    for (int x : {40, 20, 60, 10, 30, 50, 70}) root = insertAVL(root, x);
    root = deleteAVL(root, 40);
    cout << "Inorder after deleting root 40: ";
    inorder(root);
    cout << "\nRoot height: " << h(root) << "\n";
    return 0;
}
Output: Inorder after deleting root 40: 10 20 30 50 60 70 Root height: 3
3. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Five real-world systems that rely on self-balancing search trees to maintain fast lookup under sequential or dynamic updates:
  • 1. Monotonically Growing Timestamp & Log ID Indexes: Live event streams append strictly increasing timestamps/IDs—an AVL tree rebalances automatically instead of forming a slow linear chain.
  • 2. High-Read In-Memory Symbol & Route Tables: Keeps keys sorted with bounded height so lookups stay predictable even when keys arrive in order.
  • 3. Real-Time Stock / Bid-Ask Price Level Trees: Supports fast insertion, removal, and ordered traversal of active price levels as market orders stream in.
  • 4. Leaderboard & Rating Rank Queries with Frequent Updates: Maintains sorted score keys so rank or range lookups do not degrade on skewed score streams.
  • 5. File System / Disk Allocation & Interval Indexing: Tracks sorted block or range boundaries dynamically as files are created and deleted.
Python (realtime_avl_apps_1_to_5.py)
# 1. Real-Time Sequential Invoice / Event ID Index with AVL Self-Balancing
class Node:
    def __init__(self, inv_id, amount):
        self.inv_id = inv_id
        self.amount = amount
        self.left = None
        self.right = None
        self.h = 1

def h(n): return n.h if n else 0
def bf(n): return (h(n.left) - h(n.right)) if n else 0
def upd(n): n.h = 1 + max(h(n.left), h(n.right))

def rot_r(y):
    x, t2 = y.left, y.left.right
    x.right, y.left = y, t2
    upd(y); upd(x); return x

def rot_l(x):
    y, t2 = x.right, x.right.left
    y.left, x.right = x, t2
    upd(x); upd(y); return y

def insert_invoice(root, inv_id, amount):
    if not root: return Node(inv_id, amount)
    if inv_id < root.inv_id: root.left = insert_invoice(root.left, inv_id, amount)
    elif inv_id > root.inv_id: root.right = insert_invoice(root.right, inv_id, amount)
    else: root.amount = amount; return root
    upd(root)
    b = bf(root)
    if b > 1 and inv_id < root.left.inv_id: return rot_r(root)
    if b < -1 and inv_id > root.right.inv_id: return rot_l(root)
    if b > 1 and inv_id > root.left.inv_id: root.left = rot_l(root.left); return rot_r(root)
    if b < -1 and inv_id < root.right.inv_id: root.right = rot_r(root.right); return rot_l(root)
    return root

idx = None
for seq_id, amt in [(1001, 450), (1002, 1200), (1003, 890), (1004, 2300), (1005, 640), (1006, 1500)]:
    idx = insert_invoice(idx, seq_id, amt)

print(f"1. Sequential IDs 1001..1006 -> Balanced Root ID: {idx.inv_id}, Tree Height: {h(idx)}")
Output: 1. Sequential IDs 1001..1006 -> Balanced Root ID: 1004, Tree Height: 3
4. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-time domains where balanced search trees keep dynamic data fast and predictable:
  • 6. Calendar & Resource Booking Slot Trees: Stores ordered start/end slots so availability checks stay logarithmic as bookings accumulate.
  • 7. Network Firewall & Rate-Limit Rule Lookups: Evaluates numeric port or client thresholds quickly without linear list scans.
  • 8. Embedded & Real-Time Control Systems with Bounded Latency: Guarantees $O(\log n)$ worst-case search/update latency rather than occasional $O(n)$ spikes.
  • 9. Dynamic Priority / Threshold Filtering in Analytics Engines: Supports both fast single-key lookup and ordered range scans.
  • 10. Multi-User Session & Token Registry by Expiry Time: Orders active session keys so lookups and range sweeps run in logarithmic time.
Python (realtime_avl_apps_6_to_10.py)
# 6. Ordered Booking Slot Lookup with AVL Balance Verification
class SlotNode:
    def __init__(self, start_min, label):
        self.start_min = start_min
        self.label = label
        self.left = None
        self.right = None
        self.h = 1

def h(n): return n.h if n else 0
def bf(n): return (h(n.left) - h(n.right)) if n else 0
def upd(n): n.h = 1 + max(h(n.left), h(n.right))
def rr(y):
    x, t2 = y.left, y.left.right
    x.right, y.left = y, t2; upd(y); upd(x); return x
def ll(x):
    y, t2 = x.right, x.right.left
    y.left, x.right = x, t2; upd(x); upd(y); return y

def add_slot(n, k, lbl):
    if not n: return SlotNode(k, lbl)
    if k < n.start_min: n.left = add_slot(n.left, k, lbl)
    elif k > n.start_min: n.right = add_slot(n.right, k, lbl)
    else: return n
    upd(n); b = bf(n)
    if b > 1 and k < n.left.start_min: return rr(n)
    if b < -1 and k > n.right.start_min: return ll(n)
    if b > 1 and k > n.left.start_min: n.left = ll(n.left); return rr(n)
    if b < -1 and k < n.right.start_min: n.right = rr(n.right); return ll(n)
    return n

slots = None
for mins, title in [(540, "09:00"), (600, "10:00"), (660, "11:00"), (720, "12:00"), (780, "13:00")]:
    slots = add_slot(slots, mins, title)

print(f"6. Slots indexed: 5 | Root slot: {slots.label} | Max BF across root: {bf(slots)}")
Output: 6. Slots indexed: 5 | Root slot: 10:00 | Max BF across root: 1
5. Exam & Engineering Summary
Keep these practical points in mind for lab practicals, semester exams, and interviews:
  • Always update child heights before parent heights during rotations: In a right or left rotation, update the lower/rotated child first and the higher new parent second so heights stay accurate.
  • Choose between Left-Right and Right-Left carefully: If BF > +1 (left-heavy) and the inserted key goes right of the left child, it is an LR rotation (left then right); if BF < -1 (right-heavy) and the key goes left of the right child, it is an RL rotation (right then left).
  • Know when AVL vs. Red-Black is preferred: AVL trees offer tighter height and faster searches for read-heavy workloads; Red-Black trees are widely used in standard libraries (C++ std::map, Java TreeMap, Linux kernel) where write/insert/delete rotation counts are amortized.
Python (avl_tree_checklist.py)
checkpoints = [
    "AVL Balance Factor: BF = height(left) - height(right) must stay in {-1, 0, +1}.",
    "Four Rotations: LL -> Right, RR -> Left, LR -> Left-Right, RL -> Right-Left.",
    "Guaranteed O(log n): Prevents sorted-input degeneration into an O(n) skewed chain."
]

for item in checkpoints:
    print("*", item)
Output: * AVL Balance Factor: BF = height(left) - height(right) must stay in {-1, 0, +1}. * Four Rotations: LL -> Right, RR -> Left, LR -> Left-Right, RL -> Right-Left. * Guaranteed O(log n): Prevents sorted-input degeneration into an O(n) skewed chain.