AVL Tree in C and C++: Rotations, Insertion and Deletion

Build an AVL tree in C and C++: the four rotation cases, insertion and deletion, the 1.44 log n height bound, and measured heights against a plain BST.

A perfectly balanced binary tree of fifteen dark round nodes on a light gray background, with blue markers on the two outermost leaves at the same depth and a green curved arrow beside the right subtree suggesting a rotation.

An AVL tree is a binary search tree that keeps itself balanced. Every node stores a height, and when an insertion or deletion makes a node’s two sides differ by more than one, a rotation restores the balance. The measurement shows why it matters. Inserting 100,000 keys in ascending order turns a plain BST into a chain of height 99,999. The same keys in an AVL tree leave a height of 16, after 99,983 rotations.

This guide covers the balance factor, the four rotation cases, the retracing rules for insertion and deletion, and what the 1.44 log n height bound does and does not promise. It then measures height and rotation counts against an unbalanced BST. It builds on the Binary Search Tree article, which covers search, insert, delete and the ordered operations. The code was compiled and tested on Ubuntu 24.04 with GCC 13.3 and Clang 18.1.3 under AddressSanitizer and UndefinedBehaviorSanitizer, and on Windows 11 with MSVC 19.44. Both languages print byte-identical demo output.

What Is an AVL Tree?

An AVL tree is a self-balancing binary search tree, named after its inventors Adelson-Velsky and Landis, in which the two subtrees of every node differ in height by at most one. Insertions and deletions update the heights on the way back to the root and apply one of four rotations whenever the invariant breaks, which keeps the height logarithmic and every search, insert and delete O(log n) in the worst case.

The structure exists because a plain BST has no height guarantee. Its cost is the length of the search path, and that length depends on insertion order. Ascending keys make a chain, and a search at the bottom walks n nodes. Random insertion gives an expected height of about 2.99 log2 n, but an expectation is not a guarantee, and a sorted input file produces the worst case. An AVL tree removes that dependence: its height is at most about 1.44 log2 n for every insertion order.

The price is bookkeeping. Each node stores its height or a balance factor, every update refreshes heights along the path back to the root, and each rotation rewrites a few pointers. That is more work per update than a plain BST and usually more rotations than a red-black tree, which is why standard libraries choose red-black trees for ordered maps. The AVL tree remains the clearest introduction to rotation-based balancing and a good choice for read-heavy ordered sets.

The tree is an ordered set: keys are unique, in-order traversal is sorted, and search is the ordinary BST descent. Everything the Binary Trees article says about traversal applies unchanged. The B-Tree article covers the other direction, a multi-way balanced tree designed for block storage.

Every node keeps a balance factor Balance = height(left) – height(right), with heights in edges. Every factor must stay at -1, 0 or +1. 30 +1 20 +1 40 0 10 +1 25 0 35 0 50 0 5 0 Inserting 5 made 10, 20 and 30 left-heavy by one. The tree is still an AVL tree, and one more key under 5 would push 10 to +2.
Figure 1: Each node stores its height, and the balance factor is the left height minus the right height. Every factor here is 0 or +1, so the tree satisfies the AVL invariant.

How This Was Measured

SettingValue
Date testedDecember 5, 2026
HardwareIntel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300
Operating systemUbuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Windows 11 for the MSVC builds
CompilersGCC 13.3 and Clang 18.1.3 at -O2 through CMake Release, MSVC 19.44 at /W4 /WX
Height experimentN of 100, 1,000, 10,000 and 100,000. Ascending keys 1..N, plus the same keys in a fixed pseudo-random permutation
Trees comparedA plain BST built from the ascending keys, a plain BST built from the permutation, and an AVL tree built from the ascending keys
What is recordedHeight in edges, the formula value ceil(1.4405 log2(N + 2) - 0.3277), and the AVL rotation count
StatisticDeterministic integers, identical on every run and in both languages
CheckThe AVL height must stay at or below the formula value in every row, and the demo output and the table are compared across languages

The numbers are counts, not timings, so they do not depend on the machine. The sorted BST height is tracked during insertion, so the program never recurses over a chain of 100,000 nodes, and the AVL height is read from the root. The permutation uses a fixed seed, so both languages build the same random BST.

Balance Factor and the Four Rotation Cases

A node’s balance factor is height(left) - height(right). A missing child has height -1, so a leaf has height 0. The invariant is that every factor is -1, 0 or 1. When an update breaks it at some node, the shape of the break decides the fix: whether the taller subtree is on the left or the right, and which side of that subtree is taller. The four combinations are named for the path from the unbalanced node: LL and RR need one rotation, and LR and RL need two.

Rotations preserve the in-order sequence, which is why they are safe in a search tree. A right rotation moves a node down to the right of its left child, and the left child’s right subtree becomes the node’s new left subtree. The keys keep their order, the subtree’s height drops by one, and the invariant is restored locally. A double rotation is two single rotations in sequence, so the experiment counts it as two.

The details that are easy to get wrong are the height updates. After a rotation, the two nodes whose children changed need new heights, the lower node first and then the upper one. The first two pitfalls below are this class of bug: a single rotation applied to a double case, and a rotation in the wrong direction.

The four rotation cases Each case is named for the path from the unbalanced node to the new key. All four end with 20 at the root. LL: one right rotation at 30 RR: one left rotation at 10 30 20 10 rotate right 20 10 30 10 20 30 rotate left 20 10 30 LR: two rotations, left at 10, then right at 30 30 10 20 rotate left at 10 30 20 10 rotate right at 30 20 10 30 RL: two rotations, right at 30, then left at 10 10 30 20 rotate right at 30 10 20 30 rotate left at 10 20 10 30 The gold node is the one with balance +2 or -2. The experiment counts a double rotation as two rotations.
Figure 2: The four imbalance cases on three keys. LL and RR need one rotation. LR and RL rotate the child first and then the unbalanced node.

Insertion

Insertion is one pass down and one pass back up. The descent is the ordinary BST search, and if the key already exists the insert reports false and changes nothing. After the new leaf is linked, the way back up refreshes each node’s height, checks its balance and rotates where needed. An insertion raises a subtree’s height by at most one, and the rotation restores the height that subtree had before. So an insertion needs at most one single or double rotation, even though this implementation keeps walking to the root to refresh heights.

The cost is O(log n) for the descent, O(log n) for the way back and O(1) pointer work per rotation. The rotation count is a diagnostic. It shows how much of the update work is rebalancing, and the experiment records it for each size.

Deletion

Deletion is harder because it can unbalance any node on the path to the root, not just the parent of the removed node. The structural cases are the ordinary BST ones. A leaf is removed, a node with one child is replaced by that child, and a node with two children takes its in-order successor’s key, after which the successor is deleted from the right subtree. The way back up then rebalances every node whose factor left the invariant, so one deletion can rotate at several levels, up to O(log n) rotations.

Deletion reuses the rotation helpers from insertion, which is the reason to write them as functions over a node pointer. The demo’s two deletions need no rotation because the shapes they remove from stay balanced. The tests cover every deletion shape and compare the tree with a sorted reference model over 20,000 random operations.

The Height Bound and What 1.44 log n Means

The invariant bounds the height. The smallest AVL tree of height h (in edges) has F(h + 3) – 1 nodes, where F is the Fibonacci sequence, because the smallest tree of height h has a smallest tree of height h – 1 on one side and one of height h – 2 on the other. These minimal trees are called Fibonacci trees. Turned around, the count gives the familiar bound of about 1.44 log2 n, roughly 44% above the ideal log2(n + 1).

The practical reading is that an AVL tree is always shallow. With a million keys the worst case is 27 edges. The bound does not promise a perfectly balanced tree or exactly log n steps per operation. It promises that no insertion order can make the tree deeper, which is the property a plain BST lacks, and the measured sorted-BST column shows what that absence costs.

A red-black tree relaxes the balance further: its longest root-to-leaf path is at most twice its shortest, and it needs fewer rotations per update. The Red-Black Tree article measures both trees on the same keys, and the Skip List article compares the same lookups with a randomized structure that needs no rotations. That is why the C++ standard map and Java’s TreeMap are red-black trees. The AVL tree’s tighter balance makes lookups slightly cheaper and updates slightly more expensive. Both are O(log n), so the choice is a constant-factor trade.

The structure and its history are described on Wikipedia and in the NIST Dictionary of Algorithms and Data Structures. The C++ ordered map, a red-black tree, is documented on cppreference.

AVL Tree Implementation in C

The C type is a node with a key, two child pointers and a height, plus a tree struct with the root, the size and the rotation counter. The height and balance helpers are a few lines each, the four rotations are explicit pointer rewrites, and insertion and deletion are recursive functions that return the new subtree root and refresh heights on the way back.

static int node_height(const AvlNode *node)
{
    return node == NULL ? -1 : node->height;
}

/* The balance factor: positive is left-heavy, negative is right-heavy. */
static int node_balance(const AvlNode *node)
{
    return node_height(node->left) - node_height(node->right);
}

/* Recomputes the stored height from the two children. */
static void node_update(AvlNode *node)
{
    int left = node_height(node->left);
    int right = node_height(node->right);

    node->height = 1 + (left > right ? left : right);
}
static AvlNode *rotate_right(AvlTree *tree, AvlNode *node)
{
    AvlNode *pivot = node->left;

    node->left = pivot->right;
    pivot->right = node;
    node_update(node);
    node_update(pivot);
    tree->rotations++;
    return pivot;
}

/* One single left rotation at node, the RR case. */
static AvlNode *rotate_left(AvlTree *tree, AvlNode *node)
{
    AvlNode *pivot = node->right;

    node->right = pivot->left;
    pivot->left = node;
    node_update(node);
    node_update(pivot);
    tree->rotations++;
    return pivot;
}
static AvlNode *node_rebalance(AvlTree *tree, AvlNode *node)
{
    int balance;

    node_update(node);
    balance = node_balance(node);
    if (balance > 1) {
        if (node_balance(node->left) < 0)
            node->left = rotate_left(tree, node->left);
        return rotate_right(tree, node);
    }
    if (balance < -1) {
        if (node_balance(node->right) > 0)
            node->right = rotate_right(tree, node->right);
        return rotate_left(tree, node);
    }
    return node;
}

/* Inserts the preallocated fresh node into the subtree and returns the new
 * subtree root. A duplicate frees nothing and reports inserted as false. */
static AvlNode *node_insert(AvlTree *tree, AvlNode *node, AvlNode *fresh,
                            bool *inserted)
{
    if (node == NULL) {
        *inserted = true;
        return fresh;
    }
    if (fresh->key < node->key)
        node->left = node_insert(tree, node->left, fresh, inserted);
    else if (fresh->key > node->key)
        node->right = node_insert(tree, node->right, fresh, inserted);
    else
        return node;
    return node_rebalance(tree, node);
}

Output:

AVL tree: insert, delete and rotations
insert 10, 20, 30 -> root 20, height 1, rotations 1
insert 40, 50 -> root 20, height 2, rotations 2
insert 25 -> root 30, height 2, rotations 4
inorder: 10 20 25 30 40 50
delete 10 -> root 30, height 2, size 5
delete 50 -> root 30, height 2, size 4
inorder: 20 25 30 40
search 25 -> true, search 10 -> false
final height 2, size 4, rotations 4

AVL Tree Implementation in C++

The C++ version is a class over std::unique_ptr<Node>. The pointer type expresses ownership, the rotations move unique pointers, and the class exposes the same operations and counters as the C version. The in-order helper returns a std::vector<int> for the tests and the demo.

    bool insert(int key)
    {
        bool inserted = false;
        root_ = insert_node(std::move(root_), key, inserted, rotations_);
        if (inserted)
            ++size_;
        return inserted;
    }

    // Removes key if present. Returns true only when a key was removed. A node
    // with two children keeps its place and takes its in-order successor's key;
    // the successor is unlinked from the right subtree.
    bool erase(int key)
    {
        bool erased = false;
        root_ = erase_node(std::move(root_), key, erased, rotations_);
        if (erased)
            --size_;
        return erased;
    }
    static void update_height(Node* node) noexcept
    {
        const int left = height_of(node->left.get());
        const int right = height_of(node->right.get());
        node->height = 1 + (left > right ? left : right);
    }

    // A single left rotation around node, which must have a right child. The
    // right child becomes the subtree root, node becomes its left child and the
    // right child's old left subtree becomes node's new right subtree. Both
    // stored heights are refreshed and the counter is raised by one.
    [[nodiscard]] static std::unique_ptr<Node> rotate_left(std::unique_ptr<Node> node,
                                                           long long& rotations) noexcept
    {
        std::unique_ptr<Node> new_root = std::move(node->right);
        node->right = std::move(new_root->left);
        update_height(node.get());
        new_root->left = std::move(node);
        update_height(new_root.get());
        ++rotations;
        return new_root;
    }

    // A single right rotation, the mirror image of rotate_left.
    [[nodiscard]] static std::unique_ptr<Node> rotate_right(std::unique_ptr<Node> node,
                                                            long long& rotations) noexcept
    {
        std::unique_ptr<Node> new_root = std::move(node->left);
        node->left = std::move(new_root->right);
        update_height(node.get());
        new_root->right = std::move(node);
        update_height(new_root.get());
        ++rotations;
        return new_root;
    }

    // Restores the invariant at one node after its subtree changed. A balance
    // of +2 is left heavy: the left child may itself be right heavy, which makes
    // the case LR instead of LL. A balance of -2 is the mirror image.
    [[nodiscard]] static std::unique_ptr<Node> rebalance(std::unique_ptr<Node> node,
                                                        long long& rotations) noexcept
    {
        update_height(node.get());
        const int balance = balance_of(node.get());
        if (balance > 1) {
            if (balance_of(node->left.get()) < 0)
                node->left = rotate_left(std::move(node->left), rotations);
            return rotate_right(std::move(node), rotations);
        }
        if (balance < -1) {
            if (balance_of(node->right.get()) > 0)
                node->right = rotate_right(std::move(node->right), rotations);
            return rotate_left(std::move(node), rotations);
        }
        return node;
    }

    // Inserts key into the subtree and returns the subtree's new root. A
    // duplicate stops the descent with inserted left false.
    [[nodiscard]] static std::unique_ptr<Node> insert_node(std::unique_ptr<Node> node, int key,
                                                           bool& inserted, long long& rotations)
    {
        if (node == nullptr) {
            inserted = true;
            return std::make_unique<Node>(key);
        }
        if (key < node->key)
            node->left = insert_node(std::move(node->left), key, inserted, rotations);
        else if (key > node->key)
            node->right = insert_node(std::move(node->right), key, inserted, rotations);
        else
            return node;   // the key is already in the tree
        return rebalance(std::move(node), rotations);
    }

The C++ demo prints the same ten lines as the C program, byte for byte.

Measured: Height Against a BST

The height experiment inserts the keys 1..N in ascending order into a plain BST and into the AVL tree, and the same keys in a fixed pseudo-random permutation into a second plain BST. It records each height, the formula value and the AVL rotation count.

static int avl_ascending_height(int n, int *rotations)
{
    AvlTree tree;
    int height;
    int key;

    avl_init(&tree);
    for (key = 1; key <= n; ++key) {
        if (!avl_insert(&tree, key)) {
            avl_destroy(&tree);
            out_of_memory();
        }
    }
    height = avl_height(&tree);
    *rotations = avl_rotations(&tree);
    avl_destroy(&tree);
    return height;
}

/* ceil(1.4405 * log2(N + 2) - 0.3277), the height bound the article quotes. */
static int avl_bound(int n)
{
    return (int)ceil(1.4405 * log2((double)n + 2.0) - 0.3277);
}

Output (C, identical in C++):

N        bst_sorted  bst_random  avl_height  avl_bound  avl_rotations
100      99          13          6           10         93
1000     999         24          9           15         990
10000    9999        28          13          19         9986
100000   99999       38          16          24         99983

The sorted BST is a chain in every row. Its height is exactly N – 1, because each key is the new maximum and nothing rebalances. The AVL tree built from the same keys is 6, 9, 13 and 16 edges high. That is floor(log2 N), the minimum height any binary tree of N nodes can have, so ascending input produces a perfectly packed AVL tree. The exact AVL worst cases for these sizes are 8, 13, 17 and 22, so the measured trees sit two to six levels under them.

The random BST is 13, 24, 28 and 38. That is far shallower than the sorted chain but deeper than the AVL tree, and it is one fixed permutation, so it is a sample rather than an average. The useful comparison is the sorted chain against the AVL tree: the same keys and the same comparisons, with a height ratio of more than 6,000 at the largest size.

Tree height after inserting N keys Heights in edges on a log scale. The dashed line is the tallest AVL tree that N keys can form. 1 10 100 1,000 10,000 100,000 100 1,000 10,000 100,000 N keys inserted sorted BST 99,999 random BST 38 AVL worst case 22 AVL 16 The AVL tree from ascending keys reaches floor(log2 N), the minimum height any binary tree of N nodes can have.
Figure 3: Height in edges after N insertions, on a logarithmic axis. The sorted BST grows into a chain, the random BST is one fixed permutation, and the AVL tree stays below the exact AVL worst case at every N.

Rotation Counts: What They Show

The rotation totals are 93, 990, 9,986 and 99,983. Each is N minus the number of binary digits in N: 100 – 7, 1,000 – 10, 10,000 – 14 and 100,000 – 17. On ascending input every insertion triggers exactly one single left rotation, except when the new key is a power of two, which is when the tree has just become perfect and the new key starts a new level. A separate count for this review confirmed the pattern key by key.

The count is a cost, not a score. Sorted input pays almost one rotation per insertion and gets the best possible height. A random order rotates less often: in a separate run for this review, 100,000 keys in random order needed about 0.70 rotations per insertion, counting a double rotation as two, and ended at height 19. A plain BST never rotates and pays in height instead.

Five Ways an AVL Tree Passes a Quick Test and Still Fails

Each program below compiles cleanly and prints something plausible until the line that gives it away. The two C pitfalls are in the C repository’s pitfalls/ directory and the three C++ pitfalls in the C++ repository’s. They are logic bugs, not memory errors, so the workflows rerun each one and check its output line rather than relying on a sanitizer.

1. A Single Rotation Applied to a Double Case

static Node *buggy_rebalance_root(Node *root)
{
    if (node_balance(root) > 1)
        return rotate_right(root);
    return root;
}

/* The fix: a right-heavy left child means the key went into the inner
 * subtree, so rotate left at the child before rotating right at the node. */
static Node *correct_rebalance_root(Node *root)
{
    if (node_balance(root) > 1) {
        if (node_balance(root->left) < 0)
            root->left = rotate_left(root->left);
        return rotate_right(root);
    }
    return root;
}
int main(void)
{
    Node *broken = NULL;
    Node *correct = NULL;
    int root_balance;
    int worst;

    broken = insert_plain(broken, 30);
    broken = insert_plain(broken, 10);
    broken = insert_plain(broken, 20);
    root_balance = node_balance(broken);
    puts("wrong_rotation_case: a single rotation is applied to the LR case");
    printf("insert 30, 10, 20: root %d, height %d, balance at root %d\n",
           broken->key, node_height(broken), root_balance);

    broken = buggy_rebalance_root(broken);
    printf("after the buggy single right rotation: root %d, height %d\n",
           broken->key, node_height(broken));
    worst = largest_imbalance(broken);
    printf("largest balance factor magnitude %d, invariant -1 <= balance <= 1 "
           "fails\n", worst);
    free_tree(broken);

    correct = insert_plain(correct, 30);
    correct = insert_plain(correct, 10);
    correct = insert_plain(correct, 20);
    correct = correct_rebalance_root(correct);
    printf("the correct double rotation gives root %d, height %d\n",
           correct->key, node_height(correct));
    free_tree(correct);
    return EXIT_SUCCESS;
}

Output:

wrong_rotation_case: a single rotation is applied to the LR case
insert 30, 10, 20: root 30, height 2, balance at root 2
after the buggy single right rotation: root 10, height 2
largest balance factor magnitude 2, invariant -1 <= balance <= 1 fails
the correct double rotation gives root 20, height 1

The keys 30, 10, 20 create an LR case: the root is left-heavy by two, and its left child is right-heavy. The buggy rebalance looks only at the root and applies one right rotation. The root becomes 10, the height stays 2, and the largest balance factor is still 2, so the invariant still fails. The correct fix rotates left at the child and then right at the root, which gives root 20 with height 1. A single rotation fixes only LL and RR.

2. A Rotation in the Wrong Direction

static Node *buggy_rebalance_root(Node *root)
{
    if (node_balance(root) > 1)
        return rotate_left(root);
    return root;
}

/* The fix: a left-heavy node rotates right. */
static Node *correct_rebalance_root(Node *root)
{
    if (node_balance(root) > 1)
        return rotate_right(root);
    return root;
}
int main(void)
{
    Node *broken = NULL;
    Node *correct = NULL;
    int root_balance;
    int worst;

    broken = insert_plain(broken, 50);
    broken = insert_plain(broken, 30);
    broken = insert_plain(broken, 60);
    broken = insert_plain(broken, 20);
    broken = insert_plain(broken, 10);
    root_balance = node_balance(broken);
    puts("balance_sign_reversed: a left-heavy root is rotated left, the "
         "opposite way");
    printf("insert 50, 30, 60, 20, 10: root %d, height %d, balance at root "
           "%d\n", broken->key, node_height(broken), root_balance);

    broken = buggy_rebalance_root(broken);
    printf("the bug rotates left on the positive balance: root %d, height %d\n",
           broken->key, node_height(broken));
    worst = largest_imbalance(broken);
    printf("largest balance factor magnitude %d, invariant -1 <= balance <= 1 "
           "fails\n", worst);
    free_tree(broken);

    correct = insert_plain(correct, 50);
    correct = insert_plain(correct, 30);
    correct = insert_plain(correct, 60);
    correct = insert_plain(correct, 20);
    correct = insert_plain(correct, 10);
    correct = correct_rebalance_root(correct);
    printf("the correct right rotation gives root %d, height %d\n",
           correct->key, node_height(correct));
    free_tree(correct);
    return EXIT_SUCCESS;
}

Output:

balance_sign_reversed: a left-heavy root is rotated left, the opposite way
insert 50, 30, 60, 20, 10: root 50, height 3, balance at root 2
the bug rotates left on the positive balance: root 60, height 4
largest balance factor magnitude 4, invariant -1 <= balance <= 1 fails
the correct right rotation gives root 30, height 2

The bug reverses the sign convention. A left-heavy root has a positive balance, and the correct response is a right rotation, but the broken code rotates left. From the keys 50, 30, 60, 20, 10, the root 50 has balance +2. The buggy left rotation makes 60 the root, with height 4 and a largest imbalance of 4, worse than before. The correct right rotation gives root 30 with height 2. A rotation is named for the direction the old root moves, not for the heavy side, and mixing the two is the easiest sign error in the structure.

3. Heights That Go Stale After a Rotation

Node* rotate_left(Node* node, bool fix_heights)
{
    Node* new_root = node->right;
    node->right = new_root->left;
    new_root->left = node;
    if (fix_heights) {
        update_height(node);
        update_height(new_root);
    }
    // BUG when fix_heights is false: node and new_root keep their old heights.
    return new_root;
}

// A single right rotation, the mirror image.
Node* rotate_right(Node* node, bool fix_heights)
{
    Node* new_root = node->left;
    node->left = new_root->right;
    new_root->right = node;
    if (fix_heights) {
        update_height(node);
        update_height(new_root);
    }
    return new_root;
}
int main()
{
    constexpr int kLastKey = 10;

    std::cout << "stale_height: rotations that skip their height updates leave the "
                 "next insert with a stale balance factor\n";

    Node* reference = nullptr;
    int reference_rotations = 0;
    for (int key = 1; key <= kLastKey; ++key)
        reference = insert(reference, key, true, reference_rotations);
    std::cout << "insert 1..10 with correct height updates: root " << reference->key
              << ", height " << reference->height << ", rotations " << reference_rotations
              << '\n';

    Node* broken = nullptr;
    int broken_rotations = 0;
    for (int key = 1; key <= kLastKey; ++key)
        broken = insert(broken, key, false, broken_rotations);
    std::cout << "insert 1..10 with stale rotation heights: root " << broken->key
              << ", height " << broken->height << ", rotations " << broken_rotations << '\n';
    std::cout << "real height of the stale tree: " << real_height(broken) << '\n';

    int key = 0;
    int balance = 0;
    if (find_violation(broken, key, balance))
        std::cout << "first balance-invariant violation: key " << key << " has balance "
                  << balance << '\n';

    destroy(reference);
    destroy(broken);
    return EXIT_SUCCESS;
}

Output:

stale_height: rotations that skip their height updates leave the next insert with a stale balance factor
insert 1..10 with correct height updates: root 4, height 3, rotations 6
insert 1..10 with stale rotation heights: root 4, height 5, rotations 9
real height of the stale tree: 4
first balance-invariant violation: key 4 has balance -2

The rotations inside the broken insert skip their two height updates. The next insertion then reads a stale balance factor. Ten ascending keys leave a reported height of 5 against 3 for the correct code, the real height of the broken tree is 4, and key 4 violates the invariant with balance -2. The broken version also performs 9 rotations instead of 6, because the stale heights trigger rotations that the real shape never needed.

4. Deletion Without Retracing

Node* erase(Node* node, int key, bool retrace)
{
    if (node == nullptr)
        return nullptr;
    if (key < node->key) {
        node->left = erase(node->left, key, retrace);
    } else if (key > node->key) {
        node->right = erase(node->right, key, retrace);
    } else {
        if (node->left == nullptr || node->right == nullptr) {
            Node* child = node->left != nullptr ? node->left : node->right;
            delete node;
            return child;
        }
        Node* successor = node->right;
        while (successor->left != nullptr)
            successor = successor->left;
        node->key = successor->key;
        node->right = erase(node->right, successor->key, retrace);
    }
    return retrace ? rebalance(node) : node;
}
int main()
{
    std::cout << "delete_without_rebalance: a delete that unlinks without retracing "
                 "leaves stale heights behind\n";

    Node* broken = build();
    std::cout << "build 1..10 ascending: root " << broken->key << ", height "
              << broken->height << '\n';
    for (int key = 10; key >= 6; --key)
        broken = erase(broken, key, false);
    std::cout << "delete 10 down to 6 without retracing: root " << broken->key
              << ", reported height " << broken->height << ", real height "
              << real_height(broken) << '\n';

    Node* reference = build();
    for (int key = 10; key >= 6; --key)
        reference = erase(reference, key, true);
    std::cout << "delete the same keys with retracing: root " << reference->key
              << ", height " << reference->height << '\n';

    destroy(broken);
    destroy(reference);
    return EXIT_SUCCESS;
}

Output:

delete_without_rebalance: a delete that unlinks without retracing leaves stale heights behind
build 1..10 ascending: root 4, height 3
delete 10 down to 6 without retracing: root 4, reported height 3, real height 2
delete the same keys with retracing: root 4, height 2

Deleting the keys 10 down to 6 without retracing leaves the reported height at 3 while the real height is 2. The same deletions with retracing leave a height of 2. No ancestor’s height was refreshed, so the stored values are stale, and the next insertion bases its rotation decisions on them. Every deletion has to refresh and rebalance every node on the way back to the root.

5. Duplicate Keys in an Ordered Set

Node* insert_duplicates(Node* node, int key)
{
    if (node == nullptr)
        return new Node{key, nullptr, nullptr};
    if (key < node->key)
        node->left = insert_duplicates(node->left, key);
    else
        node->right = insert_duplicates(node->right, key);
    return node;
}

// The correct unique-key insert: a key equal to the node key is rejected.
Node* insert_unique(Node* node, int key)
{
    if (node == nullptr)
        return new Node{key, nullptr, nullptr};
    if (key < node->key)
        node->left = insert_unique(node->left, key);
    else if (key > node->key)
        node->right = insert_unique(node->right, key);
    return node;   // key == node->key: nothing is inserted
}

int size_of(const Node* node)
{
    if (node == nullptr)
        return 0;
    return 1 + size_of(node->left) + size_of(node->right);
}

void print_inorder(const Node* node, bool& first)
{
    if (node == nullptr)
        return;
    print_inorder(node->left, first);
    std::cout << (first ? "" : " ") << node->key;
    first = false;
    print_inorder(node->right, first);
}

void print_tree(const char* label, const Node* node)
{
    std::cout << label << ' ';
    bool first = true;
    print_inorder(node, first);
    std::cout << '\n';
}

Output:

duplicate_keys: insert() compares with < only, so an equal key becomes a right child
inorder with duplicates: 10 10 10 20 20
size with duplicates: 5
inorder with the equality check: 10 20
size with the equality check: 2

The broken insert branches on < only, so an equal key becomes a right child. Inserting 10 three times and 20 twice gives the in-order sequence 10 10 10 20 20 and a size of 5. With the equality check, the same calls give 10 20 and a size of 2. An ordered set has to test for equality before choosing a side, or every count that depends on uniqueness is wrong.

Key Takeaways

  • An AVL tree is a BST that stores a height at every node and keeps every balance factor at -1, 0 or 1, restoring it with rotations after updates.
  • There are four imbalance cases: LL and RR need one rotation, LR and RL need two.
  • An insertion needs at most one single or double rotation. A deletion can rotate at several levels on the way to the root.
  • The height is at most about 1.44 log2 n for any insertion order. Here, 100,000 ascending keys gave an AVL height of 16 against a sorted BST chain of 99,999.
  • The exact worst case comes from Fibonacci trees: 22 edges for 100,000 keys and 27 for a million.
  • Ascending insertion rotated on every key except the powers of two, 99,983 times for 100,000 keys. A random order rotated about 0.70 times per key.
  • The five pitfalls are logic bugs that compile cleanly: wrong case, wrong direction, stale heights, missing retrace and duplicate keys.

Frequently Asked Questions

Conclusion

The AVL tree adds one integer per node and a handful of rotations to a plain BST, and that is enough to turn a 99,999-edge chain into a tree of height 16. The four cases reduce to one rule: rotate toward the short side, and rotate the child first when the heavy grandchild is on the inner side. The measured rotation counts show the price, almost one per key for sorted input, and the Fibonacci bound shows why the height can never drift beyond about 1.44 log2 n.

The data structures hub places the AVL tree beside the BST, the binary trees and the B-tree. Use std::map or a red-black tree when you want a library container, and write an AVL tree when you need guaranteed shallow search and control over every rotation.

Source Code and Tests

The programs on this page are in the data-structures/avl-tree directory of two MYCPLUS example repositories:

LanguageRepository directoryBuild status
Cmycplus/c-examples: data-structures/avl-treeC AVL tree build status
C++mycplus/cpp-examples: data-structures/avl-treeC++ AVL tree build status

The examples build and test with CMake:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

The demo’s output is compared byte for byte with tests/expected/ordered.txt. The tests cover the four rotation cases, every deletion shape, duplicate rejection, the stored heights and balance factors after each operation, and a random differential test against a sorted reference model. The pitfalls are checked by their output lines. The height experiment deliberately builds the 100,000-node sorted chain, so it takes several seconds in Release and longer under sanitizers.

What I Verified

The example directories contain the test programs and the captured runs. The table states which system ran each check.

CheckUbuntu 24.04 (WSL2)Windows 11 (MSVC)
Build and tests, C, GCC 13.3, C11 and C17Pass (5 of 5 tests)Not applicable
Build and tests, C, Clang 18.1.3, C11 and C17Pass (5 of 5 tests)Not applicable
Build and tests, C, MSVC 19.44 /W4 /WXNot applicablePass (5 of 5 tests)
Build and tests, C++, g++ 13.3, C++17 and C++20Pass (6 of 6 tests)Not applicable
Build and tests, C++, clang++ 18.1.3, C++17 and C++20Pass (6 of 6 tests)Not applicable
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive-Not applicablePass (6 of 6 tests)
AddressSanitizer and UndefinedBehaviorSanitizer, tests and demoPass (C 5 of 5, C++ 6 of 6)Not applicable
Five pitfalls, each printing its documented linePassNot applicable
Height experiment, C and C++Run, identical tables, output aboveNot run
Independent rerun on a second Linux x86-64 machine (GCC 13.3, Clang 18.1.3)Pass (C 5 of 5 and C++ 6 of 6 with both compilers, demo, height table and all five pitfalls identical to the captures)Not applicable
Independent model check (Python)Ascending rotation counts, heights and the power-of-two pattern reproduced, Fibonacci worst-case heights computedNot applicable

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, deletion-heavy workloads, and insertion orders other than ascending and one fixed permutation.

Scroll to Top