Skip to content
Laviyx Learn

Try

DS Lab · Experiment 15

AVL tree insertion and search

CTreesJNTUH R22 · CS306PC

Aim

To write a C program that implements an AVL tree with insertion (including LL, RR, LR and RL rotations) and search, and displays the tree with the balance factor of every node.

Algorithm

  1. Each node stores its key, its height and pointers to its left and right children. The balance factor of a node is height(left subtree) − height(right subtree). In an AVL tree it must be −1, 0 or +1 for every node.
  2. Insert the key as in a binary search tree, recursively.
  3. On the way back up from the recursion, update the height of each node and find its balance factor.
  4. If the balance factor is +2 and the key went into the left child's left subtree (LL case), do a right rotation at the node.
  5. If it is −2 and the key went into the right child's right subtree (RR case), do a left rotation.
  6. If it is +2 and the key went into the left child's right subtree (LR case), left-rotate the left child and then right-rotate the node. If it is −2 and the key went into the right child's left subtree (RL case), right-rotate the right child and then left-rotate the node.
  7. Search as in a binary search tree. Display the tree sideways with balance factors, and its inorder and preorder traversals. Free all nodes.

Program

C
#include <stdio.h>
#include <stdlib.h>

#define MAX_INPUT 20

struct node {
    int key;
    int height;                 /* height of the subtree rooted here; a leaf has height 1 */
    struct node *left, *right;
};

int height(struct node *n) {
    return n == NULL ? 0 : n->height;
}

int max(int a, int b) {
    return a > b ? a : b;
}

void update_height(struct node *n) {
    n->height = 1 + max(height(n->left), height(n->right));
}

int balance_factor(struct node *n) {
    return height(n->left) - height(n->right);
}

struct node *new_node(int key) {
    struct node *n = malloc(sizeof(struct node));
    if (n == NULL) {
        printf("Memory not available\n");
        exit(1);
    }
    n->key = key;
    n->height = 1;
    n->left = n->right = NULL;
    return n;
}

/*      y              x
       / \            / \
      x   T3   ->   T1   y
     / \                / \
    T1  T2             T2  T3     */
struct node *rotate_right(struct node *y) {
    struct node *x = y->left;
    struct node *t2 = x->right;
    x->right = y;
    y->left = t2;
    update_height(y);           /* y is now below x, so update it first */
    update_height(x);
    return x;
}

struct node *rotate_left(struct node *x) {
    struct node *y = x->right;
    struct node *t2 = y->left;
    y->left = x;
    x->right = t2;
    update_height(x);
    update_height(y);
    return y;
}

struct node *insert(struct node *node, int key) {
    if (node == NULL) {
        return new_node(key);
    }
    if (key < node->key) {
        node->left = insert(node->left, key);
    } else if (key > node->key) {
        node->right = insert(node->right, key);
    } else {
        printf("  %d is already in the tree, skipped\n", key);
        return node;
    }

    update_height(node);
    int bf = balance_factor(node);

    if (bf > 1 && key < node->left->key) {
        printf("  LL imbalance at %d: right rotation at %d\n", node->key, node->key);
        return rotate_right(node);
    }
    if (bf < -1 && key > node->right->key) {
        printf("  RR imbalance at %d: left rotation at %d\n", node->key, node->key);
        return rotate_left(node);
    }
    if (bf > 1 && key > node->left->key) {
        printf("  LR imbalance at %d: left rotation at %d, then right rotation at %d\n",
               node->key, node->left->key, node->key);
        node->left = rotate_left(node->left);
        return rotate_right(node);
    }
    if (bf < -1 && key < node->right->key) {
        printf("  RL imbalance at %d: right rotation at %d, then left rotation at %d\n",
               node->key, node->right->key, node->key);
        node->right = rotate_right(node->right);
        return rotate_left(node);
    }
    return node;                /* already balanced */
}

int search(struct node *root, int key) {
    while (root != NULL) {
        if (key == root->key) {
            return 1;
        }
        root = (key < root->key) ? root->left : root->right;
    }
    return 0;
}

/* Sideways tree: root on the left, right subtree above, left subtree below */
void print_tree(struct node *root, int level) {
    if (root == NULL) {
        return;
    }
    print_tree(root->right, level + 1);
    for (int i = 0; i < level; i++) {
        printf("        ");
    }
    printf("%d(%d)\n", root->key, balance_factor(root));
    print_tree(root->left, level + 1);
}

void inorder(struct node *root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->key);
        inorder(root->right);
    }
}

void preorder(struct node *root) {
    if (root != NULL) {
        printf("%d ", root->key);
        preorder(root->left);
        preorder(root->right);
    }
}

void free_tree(struct node *root) {
    if (root != NULL) {
        free_tree(root->left);
        free_tree(root->right);
        free(root);
    }
}

int main(void) {
    struct node *root = NULL;
    int n, key;

    printf("Enter number of keys (1-%d): ", MAX_INPUT);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX_INPUT) {
        printf("Invalid number of keys\n");
        return 1;
    }
    printf("Enter %d keys: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &key) != 1) {
            printf("Invalid input\n");
            free_tree(root);
            return 1;
        }
        printf("Insert %d\n", key);
        root = insert(root, key);
    }

    printf("\nAVL tree, key(balance factor), turned sideways:\n");
    print_tree(root, 0);
    printf("Inorder : ");
    inorder(root);
    printf("\nPreorder: ");
    preorder(root);
    printf("\nHeight  : %d\n", height(root));

    while (1) {
        printf("\nEnter key to search (-1 to stop): ");
        if (scanf("%d", &key) != 1 || key == -1) {
            break;
        }
        printf("%d is %s\n", key, search(root, key) ? "found" : "not found");
    }

    free_tree(root);
    return 0;
}

Output

Output
Enter number of keys (1-20): 9
Enter 9 keys: 10 20 30 40 50 25 5 4 8
Insert 10
Insert 20
Insert 30
  RR imbalance at 10: left rotation at 10
Insert 40
Insert 50
  RR imbalance at 30: left rotation at 30
Insert 25
  RL imbalance at 20: right rotation at 40, then left rotation at 20
Insert 5
Insert 4
  LL imbalance at 10: right rotation at 10
Insert 8
  LR imbalance at 20: left rotation at 5, then right rotation at 20

AVL tree, key(balance factor), turned sideways:
                50(0)
        40(-1)
30(1)
                        25(0)
                20(-1)
        10(0)
                        8(0)
                5(0)
                        4(0)
Inorder : 4 5 8 10 20 25 30 40 50 
Preorder: 30 10 5 4 8 20 25 40 50 
Height  : 4

Enter key to search (-1 to stop): 25
25 is found

Enter key to search (-1 to stop): 35
35 is not found

Enter key to search (-1 to stop): -1

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

The input is chosen so that all four rotation cases happen. Checking by hand: 30 makes 10 → 20 → 30 lean right (RR at 10). 50 does the same below 20's right child (RR at 30). 25 goes left of 30, inside the right subtree of 20 (RL at 20), and 25's parent 30 becomes the root. 4 makes 10 → 5 → 4 lean left (LL at 10). 8 goes below 10, in the right subtree of 5, and 5 is the left child of 20 (LR at 20). The final tree is:

Text
             30
          /      \
        10        40
       /  \         \
      5    20        50
     / \     \
    4   8     25

In the sideways picture the number in brackets is the balance factor. Every node shows −1, 0 or 1, so the tree is balanced. The program covers insertion and search; deletion (which can need rotations at several levels) is not included.

Common mistakes

  • Updating the heights in the wrong order after a rotation. The node that moved down must be updated first, because the new parent's height depends on it.

  • Mixing up the cases: LR needs a left rotation at the left child first and then a right rotation at the node, not two right rotations.

  • Checking balance only at the root. The imbalance must be checked at every node on the path back up from the inserted node; the first unbalanced node is the one to fix.

  • Forgetting to store the returned subtree root (node->left = rotate_left(node->left);), so the rotation is lost.

Viva questions

Try to answer each one aloud before you open it.

  • What is an AVL tree?

    A self-balancing binary search tree in which, for every node, the heights of the left and right subtrees differ by at most 1. It is named after its inventors Adelson-Velsky and Landis.

  • What is the balance factor, and what values are allowed?

    Balance factor = height of left subtree − height of right subtree. In an AVL tree it must be −1, 0 or +1 at every node.

  • What are the four rotation cases?

    LL (fixed by a single right rotation), RR (single left rotation), LR (left rotation at the child, then right rotation at the node) and RL (right rotation at the child, then left rotation at the node).

  • What is the time complexity of search and insert in an AVL tree?

    O(log n) in the worst case, because the height of an AVL tree is always O(log n). A rotation itself takes O(1).

  • How many rotations can one insertion need?

    At most one single or one double rotation. After it, the subtree has the same height as before the insertion, so the nodes above it stay balanced.

Learn the concepts

All Data Structures Lab experiments →