00:00

AVL Tree Data Structure

Last updated:

An AVL tree is a height-balanced binary search tree: at every node, the heights of the left and right subtrees differ by at most 1. Whenever an insertion or deletion would break this rule, the tree repairs itself with rotations, so its height always stays O(log n).

The AVL tree was the first self-balancing binary search tree. It was published in 1962 by Georgy Adelson-Velsky and Evgenii Landis, whose initials give it its name.

A valid AVL tree with balance factorsRoot 50 has children 30 and 70. 30 has children 20 and 40; 20 has left child 10. 70 has children 60 and 80; 80 has right child 90. Balance factors: 50 is 0, 30 is +1, 70 is -1, 20 is +1, 80 is -1, all leaves are 0. Every node is between -1 and +1, so the tree is balanced.50030+170−120+140060080−1100900

balanced nodeunbalanced node (balance factor +2 or −2)+1balance factor

A valid AVL tree. The pill beside each node shows its balance factor; every value is −1, 0 or +1.

Every node of an AVL tree has a balance factor of −1, 0 or +1. The balance factor is the difference between the heights of the node's two subtrees. On this site (and in the program below) it is computed as

Balance factor = height(left subtree) − height(right subtree)

so a positive value means the left side is taller and a negative value means the right side is taller. (Some books subtract the other way round; only the sign convention changes.)

AVL Trees Rotations

A rotation is a small local change that moves one node up and its parent down while keeping the binary-search-tree order. When a node's balance factor becomes +2 or −2 after an update, one of four repairs restores the balance:

Types of AVL rotationAVL rotations are single rotations (left rotation for the right-right case, right rotation for the left-left case) or double rotations (left-right and right-left).AVL rotationsSingle rotationDouble rotationLeft rotationRR caseRight rotationLL caseLeft-RightLR caseRight-LeftRL case
Single rotations fix a straight-line imbalance; double rotations fix a zig-zag. The case name under each box is the textbook name used in the table below.

The left and right rotations are single rotations; the left-right and right-left rotations are double rotations made of two single rotations. The names used on this page follow the diagrams; the table also shows the common textbook name of the case each rotation repairs.

Imbalance at node nTextbook caseRepair
Right subtree too tall, new key went into the right child's right subtreeRight-Right (RR)Single left rotation at n
Left subtree too tall, new key went into the left child's left subtreeLeft-Left (LL)Single right rotation at n
Left subtree too tall, new key went into the left child's right subtreeLeft-Right (LR)Left rotation at the left child, then right rotation at n
Right subtree too tall, new key went into the right child's left subtreeRight-Left (RL)Right rotation at the right child, then left rotation at n

Left Rotation (LL Rotation)

A left rotation is used when a node's right side has become too tall in a straight line. The right child moves up to take the node's place, and the node becomes its left child.

For example, insert 10, 20, 30 into an empty AVL tree. The keys form a chain leaning to the right, and node 10 gets a balance factor of −2. A left rotation at 10 makes 20 the root with children 10 and 30.

Left rotationAfter inserting 10, 20 and 30 the nodes form a chain leaning right and node 10 has balance factor -2. A left rotation at 10 moves 20 up: 20 becomes the root with left child 10 and right child 30, and every balance factor is 0.10−220−1300left rotationat 10200100300Insert 10, 20, 30: node 10 is unbalanced (−2)Balanced: 20 is the new root
Left rotation: the right child (20) moves up and the unbalanced node (10) becomes its left child.

Right Rotation (RR Rotation)

A right rotation is the mirror image: it is used when a node's left side has become too tall in a straight line. The left child moves up and the node becomes its right child.

For example, insert 30, 20, 10. The keys form a chain leaning to the left, and node 30 gets a balance factor of +2. A right rotation at 30 makes 20 the root with children 10 and 30.

Right rotationAfter inserting 30, 20 and 10 the nodes form a chain leaning left and node 30 has balance factor +2. A right rotation at 30 moves 20 up: 20 becomes the root with left child 10 and right child 30.30+220+1100right rotationat 30200100300Insert 30, 20, 10: node 30 is unbalanced (+2)Balanced: 20 is the new root
Right rotation: the left child (20) moves up and the unbalanced node (30) becomes its right child.

Left Right Rotation (LR Rotation)

A left-right rotation fixes a "zig-zag" on the left: the node's left side is too tall, but the extra height is in the left child's right subtree. A single right rotation would not help, so the left child is first rotated left (which turns the zig-zag into a straight line) and then the node is rotated right.

For example, insert 30, 10, 20. Node 30 has balance factor +2 and its left child 10 has balance factor −1. Rotating 10 left gives the chain 30 → 20 → 10, and rotating 30 right makes 20 the root with children 10 and 30.

Left-right rotationAfter inserting 30, 10 and 20, node 30 has balance factor +2 and its left child 10 has -1, a zig-zag. First a left rotation at 10 turns it into the chain 30, 20, 10. Then a right rotation at 30 makes 20 the root with children 10 and 30.30+210−1200left at 1030+220+1100right at 30200100300Insert 30, 10, 20: zig-zagStep 1: now a straight chainStep 2: balanced
Left-right rotation: a left rotation at 10 straightens the zig-zag, then a right rotation at 30 balances the tree.

Right Left Rotation (RL Rotation)

A right-left rotation is the mirror image: the node's right side is too tall, but the extra height is in the right child's left subtree. The right child is first rotated right, and then the node is rotated left.

For example, insert 10, 30, 20. Node 10 has balance factor −2 and its right child 30 has balance factor +1. Rotating 30 right gives the chain 10 → 20 → 30, and rotating 10 left makes 20 the root with children 10 and 30.

Right-left rotationAfter inserting 10, 30 and 20, node 10 has balance factor -2 and its right child 30 has +1, a zig-zag. First a right rotation at 30 turns it into the chain 10, 20, 30. Then a left rotation at 10 makes 20 the root with children 10 and 30.10−230+1200right at 3010−220−1300left at 10200100300Insert 10, 30, 20: zig-zagStep 1: now a straight chainStep 2: balanced
Right-left rotation: a right rotation at 30 straightens the zig-zag, then a left rotation at 10 balances the tree.

Operations on an AVL Trees

An AVL tree supports the same operations as any binary search tree, all in O(log n) time in the worst case:

  • Search
  • Insertion
  • Deletion

Search Operation in AVL Tree

Searching works exactly as in a binary search tree and does not change the tree:

  1. Start at the root.
  2. If the key equals the current node's key, the search succeeds.
  3. If the key is smaller, continue in the left subtree; if it is larger, continue in the right subtree.
  4. If the search reaches an empty subtree (null), the key is not in the tree.

Because the height is O(log n), at most O(log n) nodes are compared.

Insertion Operation in AVL Tree

  1. Insert the key as in a binary search tree; the new node is always a leaf.
  2. Walk back up from the new node towards the root, updating each node's height and balance factor.
  3. At the first node whose balance factor becomes +2 or −2, apply the matching rotation (LL, RR, LR or RL case). After one single or double rotation the whole tree is balanced again.

Insertion takes O(log n) time.

Deletion Operation in AVL Tree

  1. Delete the key as in a binary search tree (a node with two children is replaced by its inorder successor).
  2. Walk back up from the removed position towards the root, updating heights and balance factors.
  3. Rotate at every node whose balance factor has become +2 or −2. Unlike insertion, a deletion can need a rotation at several levels, up to O(log n) of them.

Deletion also takes O(log n) time.

Implementation of AVL Tree in Java

The program below implements insertion, deletion and search. All rebalancing happens in one method, rebalance(), which is called on every node along the path back to the root. Heights are counted in nodes (a leaf has height 1), and the printout shows each node's balance factor.

AVLTree.java
// An AVL tree of int keys: a binary search tree that rebalances itself
// after every insertion and deletion so that, at every node, the heights
// of the two subtrees differ by at most 1.
public class AVLTree {

  private static class Node {
    int key;
    int height = 1;          // height counted in nodes: a leaf has height 1
    Node left, right;

    Node(int key) {
      this.key = key;
    }
  }

  private Node root;

  private static int height(Node n) {
    return (n == null) ? 0 : n.height;
  }

  // balance factor = height(left subtree) - height(right subtree)
  private static int balance(Node n) {
    return (n == null) ? 0 : height(n.left) - height(n.right);
  }

  private static void updateHeight(Node n) {
    n.height = 1 + Math.max(height(n.left), height(n.right));
  }

  // Right rotation: the left child moves up and n becomes its right child
  private static Node rotateRight(Node n) {
    Node l = n.left;
    n.left = l.right;
    l.right = n;
    updateHeight(n);
    updateHeight(l);
    return l;
  }

  // Left rotation: the right child moves up and n becomes its left child
  private static Node rotateLeft(Node n) {
    Node r = n.right;
    n.right = r.left;
    r.left = n;
    updateHeight(n);
    updateHeight(r);
    return r;
  }

  // Restores the AVL property at n (if needed) and returns the subtree's new root
  private static Node rebalance(Node n) {
    updateHeight(n);
    int bf = balance(n);
    if (bf > 1) {                        // left side is too tall
      if (balance(n.left) < 0) {
        n.left = rotateLeft(n.left);     // left-right case: first a left rotation
      }
      return rotateRight(n);             // left-left case: one right rotation
    }
    if (bf < -1) {                       // right side is too tall
      if (balance(n.right) > 0) {
        n.right = rotateRight(n.right);  // right-left case: first a right rotation
      }
      return rotateLeft(n);              // right-right case: one left rotation
    }
    return n;                            // already balanced
  }

  public void insert(int key) {
    root = insert(root, key);
  }

  private static Node insert(Node n, int key) {
    if (n == null) {
      return new Node(key);              // new keys always start as leaves
    }
    if (key < n.key) {
      n.left = insert(n.left, key);
    } else if (key > n.key) {
      n.right = insert(n.right, key);
    } else {
      return n;                          // duplicate keys are ignored
    }
    return rebalance(n);
  }

  public void delete(int key) {
    root = delete(root, key);
  }

  private static Node delete(Node n, int key) {
    if (n == null) {
      return null;                       // key not found
    }
    if (key < n.key) {
      n.left = delete(n.left, key);
    } else if (key > n.key) {
      n.right = delete(n.right, key);
    } else {
      if (n.left == null) return n.right;   // zero or one child
      if (n.right == null) return n.left;
      Node successor = n.right;             // two children: use the inorder successor
      while (successor.left != null) {
        successor = successor.left;
      }
      n.key = successor.key;
      n.right = delete(n.right, successor.key);
    }
    return rebalance(n);
  }

  public boolean contains(int key) {
    Node n = root;
    while (n != null) {
      if (key == n.key) return true;
      n = (key < n.key) ? n.left : n.right;
    }
    return false;
  }

  public void printPreorder() {
    printPreorder(root);
    System.out.println();
  }

  private static void printPreorder(Node n) {
    if (n == null) return;
    System.out.print(n.key + " ");
    printPreorder(n.left);
    printPreorder(n.right);
  }

  public void printTree() {
    print(root, "", "root");
  }

  // One node per line, indented by depth, with its balance factor
  private static void print(Node n, String indent, String label) {
    if (n == null) return;
    System.out.println(indent + label + ": " + n.key + " (bf " + balance(n) + ")");
    print(n.left, indent + "    ", "L");
    print(n.right, indent + "    ", "R");
  }

  public static void main(String[] args) {
    AVLTree tree = new AVLTree();

    // Sorted input would make a plain BST a chain; the AVL tree stays balanced
    int[] keys = {10, 20, 30, 40, 50, 25};
    for (int key : keys) {
      tree.insert(key);
    }
    System.out.println("After inserting 10, 20, 30, 40, 50, 25:");
    tree.printTree();
    System.out.print("Preorder: ");
    tree.printPreorder();

    tree.delete(40);
    System.out.println();
    System.out.println("After deleting 40:");
    tree.printTree();
    System.out.print("Preorder: ");
    tree.printPreorder();

    System.out.println("Contains 25? " + tree.contains(25));
  }
}
Output
After inserting 10, 20, 30, 40, 50, 25:
root: 30 (bf 0)
    L: 20 (bf 0)
        L: 10 (bf 0)
        R: 25 (bf 0)
    R: 40 (bf -1)
        R: 50 (bf 0)
Preorder: 30 20 10 25 40 50 

After deleting 40:
root: 30 (bf 1)
    L: 20 (bf 0)
        L: 10 (bf 0)
        R: 25 (bf 0)
    R: 50 (bf 0)
Preorder: 30 20 10 25 50 
Contains 25? true

Inserting the sorted keys 10, 20, 30, 40, 50 triggers two single left rotations; inserting 25 then triggers a right-left double rotation at 20. Deleting 40 leaves 30 with balance factor +1, which is still allowed, so no rotation is needed.

Applications of AVL Trees

  • In-memory ordered maps and sets that are searched much more often than they are changed.
  • Symbol tables in compilers and interpreters.
  • Look-up structures such as dictionaries, routing tables or configuration indexes that are built once and then queried heavily.
  • Real-time systems that need a guaranteed O(log n) bound on every operation.

Advantages of AVL Trees

  • Guaranteed O(log n) search, insertion and deletion, whatever order the keys arrive in.
  • Very balanced: the height is at most about 1.44 log2 n, lower than a red-black tree's bound, so searches need slightly fewer comparisons.
  • Keeps keys sorted, so ordered traversal and range queries are simple.
  • Insertion needs at most one single or double rotation.

Disadvantages of AVL Trees

  • More complex than a plain BST because of the rotations and height bookkeeping.
  • More rebalancing work on updates: deletion may rotate at many levels, so update-heavy workloads are usually faster with a red-black tree.
  • Extra field per node for the height or balance factor.
  • Slower than a hash table for plain key lookups when order is not needed.

When to Use AVL Trees in Applications

An AVL tree is a good fit when:

  • the data must stay sorted and every operation needs a guaranteed O(log n) bound;
  • lookups are much more frequent than insertions and deletions, so the stricter balance pays off;
  • the data set is large and lives in memory.

When to Avoid AVL Trees in Applications

Another structure is usually better when:

  • the workload is dominated by insertions and deletions: a red-black tree does less rebalancing;
  • the data is small or never changes: a sorted array with binary search is simpler;
  • order is not needed: a hash table gives O(1) average lookups;
  • the data is stored on disk: B-trees and B+ trees read many keys per disk access.

Alternatives of AVL Trees in Data Structure

ScenarioUse alternative Data Structure
Frequent insertions and deletionsRed-black tree
Small or static dataSorted array with binary search
Lookups only, no ordering neededHash table
Data stored on disk (databases, file systems)B-tree / B+ tree
Simple code, random input orderPlain BST (no worst-case guarantee) or a skip list

Difference between AVL Tree and Red-Black

FeatureAVL TreeRed-Black Tree
Balance ruleSubtree heights differ by at most 1Colour rules (no red-red, equal black height)
Maximum heightAbout 1.44 log2 nAbout 2 log2(n + 1)
SearchSlightly faster (shorter tree)Slightly slower
Insertion/DeletionMore rebalancing (deletion may rotate at every level)Fewer rotations (at most 2 for insert, 3 for delete)
Extra data per nodeHeight or balance factor (−1, 0, +1)One colour bit
Typical useLookup-heavy workloadsGeneral-purpose libraries (Java TreeMap)