M20 · Balanced Trees

AVL Trees and Rotations, with Red-Black Trees and B-Trees

A binary search tree is only as fast as it is shallow. An AVL tree stores a height in every node and, after each insert, walks back up repairing heights; where a node becomes lopsided by two levels it performs one single or double rotation. This lesson traces the four cases step by step, proves the logarithmic height bound, and places AVL trees next to the red-black trees and B-trees that the standard libraries and databases actually use.

~50 minAdvancedC# · Python · Java · C++
Curriculum: M20 Balanced Trees · 1 of 1 lessons available

You will be able to

  • Compute heights and balance factors bottom-up and say when a node violates the AVL invariant.
  • Perform left and right rotations and explain why they preserve the inorder (sorted) order.
  • Classify an imbalance as LL, RR, LR or RL from the signs of two balance factors, and apply the single or double rotation that fixes it.
  • Sketch why an AVL tree with n keys has height below about 1.44 log₂ n, and why an insert needs at most one (single or double) rotation.
  • Describe red-black trees and B-trees at the level of their invariants, and compare them with AVL trees.
  • Know which balanced structure backs the ordered collections of C#, Java and C++, and what Python offers instead.

Helpful before this lesson

  • M19 Binary Search Trees — The BST invariant, its operations, and why balance decides their cost.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Why balance matters

Every operation of a binary search tree walks one root-to-node path, so it costs O(h), where h is the height. Insert the keys 1, 2, 3, …, n in that order and a plain BST becomes a chain of height n − 1: search is then a linear scan with extra pointer chasing. Nothing about the keys is wrong; only the order they arrived in was unlucky, and real data (timestamps, auto-increment IDs, sorted files) arrives in that order all the time.

A balanced search tree does a little extra work on every update so that the height stays O(log n) whatever the order. The AVL tree (Adelson-Velsky and Landis, 1962) was the first. It is still the clearest one to study, because its rule is a single number per node.

Heights and balance factors

This lesson, the lab and all four implementations count height in edges, as in the BST lesson:

  • an empty subtree has height −1, a leaf has height 0;
  • height(node) = 1 + max(height(left), height(right));
  • the balance factor is bf(node) = height(left) − height(right).

AVL invariant: every node has bf ∈ {−1, 0, +1}. The two subtrees of any node differ in height by at most one. Positive means left-heavy, negative right-heavy.

Each node stores its own height, so a balance factor costs two field reads, not a traversal. The price is keeping those stored heights correct after every change, and that is exactly where rebalancing hooks in.

Rotations

A rotation changes the shape of a subtree in O(1) without changing its inorder sequence.

        y                           x
       / \     rotate right at y   / \
      x   C    ───────────────▶   A   y
     / \       ◀───────────────      / \
    A   B      rotate left at x     B   C

Read the keys left to right in both pictures: A < x < B < y < C either way. Only three links change: y.left becomes B, x.right becomes y, and whoever pointed at y now points at x. Subtree B, the "middle" one, is the only part that changes parent. Afterwards only y and x need new heights, y first because it is now the lower of the two.

In the lab, a rotation is one step: the node moving up is violet, the node moving down teal, and because nodes are placed left to right by inorder rank you can watch every key keep its column while the levels change.

Insert: the four cases

Insert starts as a plain BST insert: compare, descend, attach a new leaf. Then the recursion unwinds, and every node on the path back to the root does three things:

insert(node, key):
    if node is empty: return new leaf             # height 0
    if key < node.key: node.left  = insert(node.left, key)
    elif key > node.key: node.right = insert(node.right, key)
    else: return node                             # duplicate: nothing changes
    return rebalance(node)

rebalance(node):
    node.height = 1 + max(height(node.left), height(node.right))
    bf = height(node.left) − height(node.right)
    if bf > 1:                                    # left-heavy
        if bf(node.left) < 0: node.left = rotate_left(node.left)    # LR
        return rotate_right(node)                                   # LL
    if bf < −1:                                   # right-heavy
        if bf(node.right) > 0: node.right = rotate_right(node.right) # RL
        return rotate_left(node)                                     # RR
    return node

After an insert, the first node on the way up whose balance factor leaves −1…+1 has bf = +2 or bf = −2. Which rotation fixes it depends on the sign of the heavy child's balance factor:

Node bf Heavy child bf Shape Case Fix
+2 +1 left child leans left (a straight line) LL rotate right at the node
−2 −1 right child leans right RR rotate left at the node
+2 −1 left child leans right (a zig-zag) LR rotate left at the child, then right at the node
−2 +1 right child leans left RL rotate right at the child, then left at the node

The single rotation fails on a zig-zag: rotating right at the node of an LR shape just produces the mirror-image zig-zag. The first half of the double rotation straightens the zig-zag into an LL shape; the second half is the ordinary LL fix. Each preset in the lab isolates one case with three keys: 30, 20, 10 (LL), 10, 20, 30 (RR), 30, 10, 20 (LR) and 10, 30, 20 (RL). All four end as the same tree, 20 with children 10 and 30.

At most one rotation per insert

Look at the subtree rooted at the unbalanced node before the insert. Say its height was h. The insert made it h + 1, which is what unbalanced it. In every one of the four cases, the rotation produces a subtree of height h again. So every ancestor above sees its child's height back at the old value: nothing above can be out of balance. Hence an insert performs at most one single or one double rotation, followed only by height updates. The Mixed preset shows this: inserting 5 unbalances 30, deep inside the tree, and one right rotation there leaves the root's balance untouched.

(The implementations still recompute heights all the way up, which is simpler and costs O(log n) anyway. They skip the whole way back up after a duplicate, when nothing changed.)

Delete

Delete is the BST delete (leaf, one child, two children via the inorder successor) followed by the same rebalance on the way up. The four cases are identical, plus one new situation: the heavy child can have balance factor 0, which deletion can produce but insertion cannot; it is handled as LL (or RR). The difference is that a rotation after a delete can lower the subtree's height, so the ancestor above may become unbalanced in turn: one delete can need a rotation at every level, O(log n) of them. The lab and the four implementations cover insert, search and the invariant check; delete adds no new rotation to see, only more of the same.

How tall can an AVL tree be?

Ask the reverse question: what is the fewest nodes N(h) an AVL tree of height h can have? The sparsest such tree has a root, one subtree of height h − 1 and, as lopsided as allowed, the other of height h − 2, each of them as sparse as possible:

N(0) = 1,  N(1) = 2,  N(h) = N(h − 1) + N(h − 2) + 1
1, 2, 4, 7, 12, 20, 33, 54, …     N(h) = F(h + 3) − 1   (F = Fibonacci: 1, 1, 2, 3, 5, 8, …)

These sparsest trees are called Fibonacci trees. Fibonacci numbers grow like φʰ with φ ≈ 1.618, so n ≥ N(h) ≈ φʰ⁺³/√5, which gives h ≤ log_φ n + O(1) ≈ 1.44 log₂ n. Knuth's exact form, counting levels rather than edges, is levels < 1.4405 log₂(n + 2) − 0.3277; all four test suites assert it on random trees. For a million keys an AVL tree has at most 28 levels, against 20 for a perfect tree and up to a million for an unlucky BST. Inserting 1 … 2ᵏ − 1 in sorted order even builds a perfect tree: the Sorted inserts stay balanced preset ends with 1 … 7 at height 2 after four rotations.

Complexity

Operation AVL tree Plain BST (worst case)
search O(log n) O(n)
insert O(log n), at most 1 single or double rotation O(n)
delete O(log n), up to O(log n) rotations O(n)
min, max, successor O(log n) O(n)
invariant check O(n) O(n)
extra space one height per node (a byte would do); O(log n) recursion stack none

Every bound is a worst case, not an average: that is the point of balancing.

Red-black trees

A red-black tree is another balanced BST, with a looser rule enforced by colouring every node red or black:

  1. The root is black, and the empty leaves (null links) count as black.
  2. A red node has no red child.
  3. Every path from a node down to an empty leaf passes the same number of black nodes, its black-height.

Rule 3 says the tree is perfectly balanced if you ignore red nodes; rule 2 says red nodes can at most double a path's length. So the longest path is at most twice the shortest, and the height is at most 2 log₂(n + 1). That is a weaker guarantee than AVL's 1.44 log₂ n, so searches can be slightly deeper. In exchange, repairs are cheaper: an insert does at most two rotations and a delete at most three, with the rest done by recolouring (which can walk up the tree but is O(1) amortized). That makes red-black trees a common default for general-purpose ordered maps with many updates; AVL trees suit lookup-heavy workloads a little better. Both are O(log n) for everything.

B-trees and B+ trees

When data lives on disk or SSD, the cost that matters is the number of pages read, not the number of comparisons. A B-tree (Bayer and McCreight, 1972) stores many keys per node, sized to fill a page:

  • a node with k keys has k + 1 children, and keys separate the children's ranges, like a BST node generalised to many keys;
  • every node except the root is at least half full (between t − 1 and 2t − 1 keys for a minimum degree t);
  • all leaves are at the same depth. The tree grows at the root (a full node splits and pushes its middle key up), never by making one branch longer.

With hundreds of keys per node, the height is O(log_t n): a few levels cover billions of keys, and the top levels usually stay cached in memory. A B+ tree keeps all records in the leaves, uses the inner nodes only for routing, and links the leaves left to right so a range scan is a sequential walk. B+ tree variants are the usual index structure in relational databases and appear in many file systems. In memory, wide nodes also help with cache lines, which is why some ordered containers use B-trees there too (not the standard ones covered below).

Comparison

AVL tree Red-black tree B-tree / B+ tree
Invariant subtree heights differ by ≤ 1 colour rules, equal black-height nodes ≥ half full, leaves at one depth
Height bound < 1.44 log₂ n ≤ 2 log₂(n + 1) O(log_t n), t = keys per node / 2
Rotations per insert ≤ 1 single or double ≤ 2 none (node splits instead)
Rotations per delete O(log n) ≤ 3 none (merges and borrows)
Stored per node a height a colour bit up to 2t − 1 keys, 2t children
Typical home in-memory, lookup-heavy in-memory library maps and sets databases, file systems (disk pages)

Built-in ordered collections

You will rarely write a balanced tree for production code; you will choose between the library ones.

Language Ordered set / map What the documentation guarantees
C# SortedSet<T>, SortedDictionary<TKey, TValue> Documented as binary search trees with O(log n) operations; in current .NET both are implemented as red-black trees. SortedList<TKey, TValue> is different: two sorted arrays, O(log n) lookup but O(n) insert and remove.
Java TreeMap<K, V>, TreeSet<E> The TreeMap Javadoc states it is a red-black tree with guaranteed log(n) containsKey, get, put and remove; TreeSet is backed by a TreeMap.
C++ std::set, std::map (and multi versions) The standard fixes the interface and logarithmic complexity, not the structure. The major implementations (libstdc++, libc++, Microsoft's STL) typically use red-black trees, but that is implementation-defined.
Python none in the standard library dict and set are hash tables (no order by key). For a sorted sequence, the bisect module searches a sorted list in O(log n), but insort must shift elements: O(n) per insert. Third-party packages such as sortedcontainers exist; they are not part of the standard library, and this course does not depend on them.

All of these give you the AVL tree's guarantees (worst-case O(log n), iteration in key order, floor and ceiling queries) without any rotation code of your own.

The teaching implementation

AvlTree / avl_tree follows the pseudocode above in all four languages: recursive Insert that returns the subtree's new root, Rebalance with the four cases, RotateLeft / RotateRight, an iterative Contains, and IsValid, which checks order, stored heights and balance factors in one postorder pass. The C++ version owns its nodes through std::unique_ptr, so a rotation moves ownership of three links. Each language runs one shared fixture that pins the exact shape (preorder), height and rotation count of every case, and 300 random insert/search sequences against its own sorted set (SortedSet<int>, set + sorted, TreeSet, std::set), checking the invariants after every operation.

Language notes

  • C#: a ref bool added parameter reports whether the recursive insert created a node. Node? nullable annotations make the "child exists" assumptions explicit (node.Left! in the rotation cases, where the balance factor guarantees the child).
  • Python: recursion depth is not a concern here, because an AVL tree of any size you can hold in memory is less than about 60 levels deep, far below the default recursion limit of 1000.
  • Java: Integer.MIN_VALUE marks a broken subtree in the checker; the bounds are long so that keys equal to Integer.MIN_VALUE or MAX_VALUE still fit strictly inside them.
  • C++: std::optional<int> expresses both "no bound" and "broken" without sentinels.

Common mistakes

  • Updating heights in the wrong order after a rotation. The node that moved down must be updated first; the node that moved up depends on it.
  • Forgetting to relink the parent. The rotation returns a new subtree root; if the caller does not store it (node.left = insert(...)), the rotated subtree is lost.
  • Using a single rotation on a zig-zag (LR or RL). It only mirrors the problem.
  • Mixing height conventions. Leaf height 0 with empty −1, or leaf 1 with empty 0, both work; mixing them makes every balance factor off by one at the leaves.
  • Recomputing heights by traversal. height() as a recursive function makes every insert O(n).

Edge cases

  • Duplicates: rejected, nothing changes, no rotation.
  • An empty tree is a valid AVL tree; check returns true and search returns false.
  • Two keys: a root and one child, balance ±1, still valid; the third key decides whether a rotation happens.
  • Extreme keys (−999 and 999 in the lab, int limits in code) need strict bounds in the checker.

Worked practice

1. Insert 10, 20, 30, 40, 50 into an empty AVL tree. Give the final preorder and the number of rotations.

Answer

30 makes 10 right-heavy (−2) with its right child leaning right: RR, rotate left at 10, giving 20 with children 10 and 30. 40 goes under 30. 50 makes 30 right-heavy (−2): RR again, rotate left at 30. Final tree: 20, left 10, right 40 with children 30 and 50. Preorder 20 10 40 30 50, two rotations, height 2. A plain BST would have height 4.

2. A node has bf = +2 and its left child has bf = −1. Name the case and the rotations, in order.

Answer

LR: rotate left at the left child (straightening the zig-zag into an LL shape), then rotate right at the node. In the lab's Case LR preset that is "rotate 10 left", then "rotate 30 right".

3. What is the smallest number of keys an AVL tree of height 4 (edges) can hold? And a plain BST?

Answer

N(4) = N(3) + N(2) + 1 = 7 + 4 + 1 = 12 for the AVL tree. A plain BST needs only 5: a chain.

4. Why can one insert never trigger rotations at two different nodes?

Answer

The rotation at the lowest unbalanced node returns that subtree to the height it had before the insert. Every ancestor's balance factor depended only on that height, which is unchanged, so every ancestor is as balanced as before the insert.

5. You need a sorted map in Python with frequent inserts and range queries over 10⁶ keys. What are your standard-library options and their costs?

Answer

A sorted list with bisect: O(log n) to find a position and to answer range boundaries, but O(n) to insert because elements shift (fast in practice thanks to memmove, but still linear). Or a dict plus sorting when needed. The standard library has no balanced tree; a third-party sorted collection or a database index would be the next step, by choice and not by default.

Summary

  • An AVL tree is a BST where every node's subtrees differ in height by at most one.
  • Insert as in a BST, then on the way up update heights and fix the first node with bf = ±2.
  • LL and RR need one rotation, LR and RL two; rotations preserve the sorted order and take O(1).
  • Height stays below about 1.44 log₂ n, so search, insert and delete are worst-case O(log n).
  • Red-black trees relax the balance (height ≤ 2 log₂(n + 1)) for cheaper updates and back the ordered collections of .NET, Java and typically C++; B-trees widen nodes to match disk pages.
  • Python's standard library has no balanced tree: use bisect on a list, or reach outside it.

Full implementation

The AVL tree in four languages, each checked against one shared fixture (return values, inorder, the exact preorder shape, height and rotation count for the LL, RR, LR and RL cases, duplicates and an empty tree) and 300 random insert/search sequences compared with the language’s sorted set, with the order, height and balance invariants verified after every operation.

namespace Bekadan.Dsa.Examples.Trees;
 
/// <summary>
/// An AVL tree of distinct int keys: a binary search tree that rebalances on
/// the way back up every insert, so its height stays below about 1.44 log2 n
/// and Insert and Contains cost O(log n) in the worst case.
/// Height is counted in edges (a leaf has height 0, an empty subtree -1);
/// balance factor = height(left) - height(right), kept in -1..+1.
/// In production code use SortedSet&lt;T&gt; / SortedDictionary&lt;TKey,TValue&gt;
/// (a balanced red-black tree in current .NET).
/// </summary>
public sealed class AvlTree
{
    private sealed class Node(int key)
    {
        public readonly int Key = key;
        public Node? Left;
        public Node? Right;
        public int Height; // 0 for a leaf
    }
 
    private Node? _root;
 
    public int Count { get; private set; }
 
    /// <summary>Single rotations performed so far (a double rotation counts two).</summary>
    public int Rotations { get; private set; }
 
    private static int HeightOf(Node? node) => node?.Height ?? -1;
 
    private static int BalanceOf(Node node) => HeightOf(node.Left) - HeightOf(node.Right);
 
    /// <summary>Adds the key; returns false if it is already present.</summary>
    public bool Insert(int key)
    {
        bool added = false;
        _root = Insert(_root, key, ref added);
        return added;
    }
 
    private Node Insert(Node? node, int key, ref bool added)
    {
        if (node is null)
        {
            added = true;
            Count++;
            return new Node(key);
        }
        if (key < node.Key)
            node.Left = Insert(node.Left, key, ref added);
        else if (key > node.Key)
            node.Right = Insert(node.Right, key, ref added);
        else
            return node; // already present: nothing changes
        return added ? Rebalance(node) : node;
    }
 
    /// <summary>Fixes the height of <paramref name="node"/> and rotates if it is out of balance. Returns the subtree's new root.</summary>
    private Node Rebalance(Node node)
    {
        node.Height = 1 + Math.Max(HeightOf(node.Left), HeightOf(node.Right));
        int balance = BalanceOf(node);
        if (balance > 1) // left-heavy
        {
            if (BalanceOf(node.Left!) < 0)
                node.Left = RotateLeft(node.Left!); // LR: straighten the zig-zag first
            return RotateRight(node); // LL (or the second half of LR)
        }
        if (balance < -1) // right-heavy
        {
            if (BalanceOf(node.Right!) > 0)
                node.Right = RotateRight(node.Right!); // RL: straighten the zig-zag first
            return RotateLeft(node); // RR (or the second half of RL)
        }
        return node;
    }
 
    private Node RotateRight(Node down)
    {
        Node up = down.Left!;
        down.Left = up.Right; // the middle subtree changes parent
        up.Right = down;
        down.Height = 1 + Math.Max(HeightOf(down.Left), HeightOf(down.Right));
        up.Height = 1 + Math.Max(HeightOf(up.Left), HeightOf(up.Right));
        Rotations++;
        return up;
    }
 
    private Node RotateLeft(Node down)
    {
        Node up = down.Right!;
        down.Right = up.Left;
        up.Left = down;
        down.Height = 1 + Math.Max(HeightOf(down.Left), HeightOf(down.Right));
        up.Height = 1 + Math.Max(HeightOf(up.Left), HeightOf(up.Right));
        Rotations++;
        return up;
    }
 
    public bool Contains(int key)
    {
        Node? node = _root;
        while (node is not null && node.Key != key)
            node = key < node.Key ? node.Left : node.Right;
        if (node is not null)
            return true;
        return false;
    }
 
    /// <summary>Checks order, stored heights and balance factors at every node. O(n).</summary>
    public bool IsValid() => Verify(_root, long.MinValue, long.MaxValue) != Broken;
 
    private const int Broken = int.MinValue;
 
    /// <summary>Returns the verified height of the subtree, or <see cref="Broken"/>.</summary>
    private static int Verify(Node? node, long low, long high)
    {
        if (node is null)
            return -1;
        if (node.Key <= low || node.Key >= high)
            return Broken;
        int left = Verify(node.Left, low, node.Key);
        int right = left == Broken ? Broken : Verify(node.Right, node.Key, high);
        bool ok = right != Broken && node.Height == 1 + Math.Max(left, right) && Math.Abs(left - right) <= 1;
        return ok ? node.Height : Broken;
    }
 
    public int Height() => HeightOf(_root);
 
    public List<int> InOrder()
    {
        var keys = new List<int>();
        void Walk(Node? n)
        {
            if (n is null) return;
            Walk(n.Left);
            keys.Add(n.Key);
            Walk(n.Right);
        }
        Walk(_root);
        return keys;
    }
 
    public List<int> PreOrder()
    {
        var keys = new List<int>();
        void Walk(Node? n)
        {
            if (n is null) return;
            keys.Add(n.Key);
            Walk(n.Left);
            Walk(n.Right);
        }
        Walk(_root);
        return keys;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Trees/AvlTree.cs

"""An AVL tree of distinct int keys.
 
A binary search tree that rebalances on the way back up every insert, so its
height stays below about 1.44 log2 n and insert and contains cost O(log n) in
the worst case. Height is counted in edges (a leaf has height 0, an empty
subtree -1); balance factor = height(left) - height(right), kept in -1..+1.
 
The standard library has no balanced search tree: for sorted data use the
bisect module on a list (O(n) inserts), or a third-party package.
"""
 
from __future__ import annotations
 
from collections.abc import Iterator
from dataclasses import dataclass
 
 
@dataclass(eq=False)
class _Node:
    key: int
    left: _Node | None = None
    right: _Node | None = None
    height: int = 0  # 0 for a leaf
 
 
def _height(node: _Node | None) -> int:
    return -1 if node is None else node.height
 
 
def _balance(node: _Node) -> int:
    return _height(node.left) - _height(node.right)
 
 
class AvlTree:
    def __init__(self) -> None:
        self._root: _Node | None = None
        self.count = 0
        self.rotations = 0  # single rotations; a double rotation counts two
 
    def insert(self, key: int) -> bool:
        """Adds the key; returns False if it is already present."""
        before = self.count
        self._root = self._insert(self._root, key)
        return self.count > before
 
    def _insert(self, node: _Node | None, key: int) -> _Node:
        if node is None:
            self.count += 1
            return _Node(key)
        before = self.count
        if key < node.key:
            node.left = self._insert(node.left, key)
        elif key > node.key:
            node.right = self._insert(node.right, key)
        else:
            return node  # already present: nothing changes
        return self._rebalance(node) if self.count > before else node
 
    def _rebalance(self, node: _Node) -> _Node:
        """Fixes node's height and rotates if it is out of balance. Returns the subtree's new root."""
        node.height = 1 + max(_height(node.left), _height(node.right))
        balance = _balance(node)
        if balance > 1:  # left-heavy
            assert node.left is not None
            if _balance(node.left) < 0:
                node.left = self._rotate_left(node.left)  # LR: straighten the zig-zag first
            return self._rotate_right(node)  # LL (or the second half of LR)
        if balance < -1:  # right-heavy
            assert node.right is not None
            if _balance(node.right) > 0:
                node.right = self._rotate_right(node.right)  # RL: straighten the zig-zag first
            return self._rotate_left(node)  # RR (or the second half of RL)
        return node
 
    def _rotate_right(self, down: _Node) -> _Node:
        up = down.left
        assert up is not None
        down.left = up.right  # the middle subtree changes parent
        up.right = down
        down.height = 1 + max(_height(down.left), _height(down.right))
        up.height = 1 + max(_height(up.left), _height(up.right))
        self.rotations += 1
        return up
 
    def _rotate_left(self, down: _Node) -> _Node:
        up = down.right
        assert up is not None
        down.right = up.left
        up.left = down
        down.height = 1 + max(_height(down.left), _height(down.right))
        up.height = 1 + max(_height(up.left), _height(up.right))
        self.rotations += 1
        return up
 
    def contains(self, key: int) -> bool:
        node = self._root
        while node is not None and node.key != key:
            node = node.left if key < node.key else node.right
        if node is not None:
            return True
        return False
 
    def is_valid(self) -> bool:
        """Checks order, stored heights and balance factors at every node. O(n)."""
        return _verify(self._root, None, None) is not None
 
    def height(self) -> int:
        return _height(self._root)
 
    def inorder(self) -> list[int]:
        return list(_inorder(self._root))
 
    def preorder(self) -> list[int]:
        return list(_preorder(self._root))
 
 
def _verify(node: _Node | None, low: int | None, high: int | None) -> int | None:
    """The verified height of the subtree, or None when something is broken."""
    if node is None:
        return -1
    if (low is not None and node.key <= low) or (high is not None and node.key >= high):
        return None
    left = _verify(node.left, low, node.key)
    right = None if left is None else _verify(node.right, node.key, high)
    if left is None or right is None:
        return None
    ok = node.height == 1 + max(left, right) and abs(left - right) <= 1
    return node.height if ok else None
 
 
def _inorder(node: _Node | None) -> Iterator[int]:
    if node is not None:
        yield from _inorder(node.left)
        yield node.key
        yield from _inorder(node.right)
 
 
def _preorder(node: _Node | None) -> Iterator[int]:
    if node is not None:
        yield node.key
        yield from _preorder(node.left)
        yield from _preorder(node.right)

Tested on CPython 3.14.0 · examples/python/dsa_examples/avl_tree.py

package dev.bekadan.dsa.trees;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * An AVL tree of distinct int keys: a binary search tree that rebalances on the way back up
 * every insert, so its height stays below about 1.44 log2 n and insert and contains cost
 * O(log n) in the worst case. Height is counted in edges (a leaf has height 0, an empty
 * subtree -1); balance factor = height(left) - height(right), kept in -1..+1. In production
 * code use {@link java.util.TreeMap} / {@link java.util.TreeSet} (red-black trees).
 */
public final class AvlTree {
    private static final class Node {
        final int key;
        Node left;
        Node right;
        int height; // 0 for a leaf
 
        Node(int key) {
            this.key = key;
        }
    }
 
    private static final int BROKEN = Integer.MIN_VALUE;
 
    private Node root;
    private int count;
    private int rotations;
    private boolean added;
 
    public int count() {
        return count;
    }
 
    /** Single rotations performed so far (a double rotation counts two). */
    public int rotations() {
        return rotations;
    }
 
    private static int heightOf(Node node) {
        return node == null ? -1 : node.height;
    }
 
    private static int balanceOf(Node node) {
        return heightOf(node.left) - heightOf(node.right);
    }
 
    /** Adds the key; returns false if it is already present. */
    public boolean insert(int key) {
        added = false;
        root = insert(root, key);
        return added;
    }
 
    private Node insert(Node node, int key) {
        if (node == null) {
            added = true;
            count++;
            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 {
            return node; // already present: nothing changes
        }
        return added ? rebalance(node) : node;
    }
 
    /** Fixes the node's height and rotates if it is out of balance. Returns the subtree's new root. */
    private Node rebalance(Node node) {
        node.height = 1 + Math.max(heightOf(node.left), heightOf(node.right));
        int balance = balanceOf(node);
        if (balance > 1) { // left-heavy
            if (balanceOf(node.left) < 0) {
                node.left = rotateLeft(node.left); // LR: straighten the zig-zag first
            }
            return rotateRight(node); // LL (or the second half of LR)
        }
        if (balance < -1) { // right-heavy
            if (balanceOf(node.right) > 0) {
                node.right = rotateRight(node.right); // RL: straighten the zig-zag first
            }
            return rotateLeft(node); // RR (or the second half of RL)
        }
        return node;
    }
 
    private Node rotateRight(Node down) {
        Node up = down.left;
        down.left = up.right; // the middle subtree changes parent
        up.right = down;
        down.height = 1 + Math.max(heightOf(down.left), heightOf(down.right));
        up.height = 1 + Math.max(heightOf(up.left), heightOf(up.right));
        rotations++;
        return up;
    }
 
    private Node rotateLeft(Node down) {
        Node up = down.right;
        down.right = up.left;
        up.left = down;
        down.height = 1 + Math.max(heightOf(down.left), heightOf(down.right));
        up.height = 1 + Math.max(heightOf(up.left), heightOf(up.right));
        rotations++;
        return up;
    }
 
    public boolean contains(int key) {
        Node node = root;
        while (node != null && node.key != key) {
            node = key < node.key ? node.left : node.right;
        }
        if (node != null) {
            return true;
        }
        return false;
    }
 
    /** Checks order, stored heights and balance factors at every node. O(n). */
    public boolean isValid() {
        return verify(root, Long.MIN_VALUE, Long.MAX_VALUE) != BROKEN;
    }
 
    /** The verified height of the subtree, or BROKEN. */
    private static int verify(Node node, long low, long high) {
        if (node == null) {
            return -1;
        }
        if (node.key <= low || node.key >= high) {
            return BROKEN;
        }
        int left = verify(node.left, low, node.key);
        int right = left == BROKEN ? BROKEN : verify(node.right, node.key, high);
        boolean ok = right != BROKEN && node.height == 1 + Math.max(left, right) && Math.abs(left - right) <= 1;
        return ok ? node.height : BROKEN;
    }
 
    public int height() {
        return heightOf(root);
    }
 
    public List<Integer> inorder() {
        List<Integer> keys = new ArrayList<>();
        inorder(root, keys);
        return keys;
    }
 
    private static void inorder(Node node, List<Integer> keys) {
        if (node == null) {
            return;
        }
        inorder(node.left, keys);
        keys.add(node.key);
        inorder(node.right, keys);
    }
 
    public List<Integer> preorder() {
        List<Integer> keys = new ArrayList<>();
        preorder(root, keys);
        return keys;
    }
 
    private static void preorder(Node node, List<Integer> keys) {
        if (node == null) {
            return;
        }
        keys.add(node.key);
        preorder(node.left, keys);
        preorder(node.right, keys);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/trees/AvlTree.java

#pragma once
 
#include <algorithm>
#include <cstdlib>
#include <limits>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// An AVL tree of distinct int keys: a binary search tree that rebalances on the way back up
// every insert, so its height stays below about 1.44 log2 n and insert and contains cost
// O(log n) in the worst case. Height is counted in edges (a leaf has height 0, an empty
// subtree -1); balance factor = height(left) - height(right), kept in -1..+1. Nodes are owned
// by std::unique_ptr, so rotations move ownership instead of copying. In production code use
// std::set / std::map (typically red-black trees; the standard fixes only their complexity).
class AvlTree {
public:
    // Adds the key; returns false if it is already present.
    bool insert(int key) {
        bool added = false;
        root_ = insert(std::move(root_), key, added);
        return added;
    }
 
    [[nodiscard]] bool contains(int key) const {
        const Node* node = root_.get();
        while (node != nullptr && node->key != key) node = key < node->key ? node->left.get() : node->right.get();
        if (node != nullptr) return true;
        return false;
    }
 
    // Checks order, stored heights and balance factors at every node. O(n).
    [[nodiscard]] bool is_valid() const { return verify(root_.get(), std::nullopt, std::nullopt).has_value(); }
 
    [[nodiscard]] int height() const noexcept { return height_of(root_.get()); }
    [[nodiscard]] std::size_t size() const noexcept { return count_; }
    // Single rotations performed so far (a double rotation counts two).
    [[nodiscard]] int rotations() const noexcept { return rotations_; }
 
    [[nodiscard]] std::vector<int> inorder() const {
        std::vector<int> keys;
        walk(root_.get(), keys, false);
        return keys;
    }
 
    [[nodiscard]] std::vector<int> preorder() const {
        std::vector<int> keys;
        walk(root_.get(), keys, true);
        return keys;
    }
 
private:
    struct Node {
        explicit Node(int k) : key(k) {}
        int key;
        int height = 0;  // 0 for a leaf
        std::unique_ptr<Node> left;
        std::unique_ptr<Node> right;
    };
    using Ptr = std::unique_ptr<Node>;
 
    static int height_of(const Node* node) noexcept { return node == nullptr ? -1 : node->height; }
    static int balance_of(const Node& node) noexcept { return height_of(node.left.get()) - height_of(node.right.get()); }
    static void fix_height(Node& node) noexcept { node.height = 1 + std::max(height_of(node.left.get()), height_of(node.right.get())); }
 
    Ptr insert(Ptr node, int key, bool& added) {
        if (!node) {
            added = true;
            ++count_;
            return std::make_unique<Node>(key);
        }
        if (key < node->key) node->left = insert(std::move(node->left), key, added);
        else if (key > node->key) node->right = insert(std::move(node->right), key, added);
        else return node;  // already present: nothing changes
        return added ? rebalance(std::move(node)) : std::move(node);
    }
 
    // Fixes the node's height and rotates if it is out of balance. Returns the subtree's new root.
    Ptr rebalance(Ptr node) {
        fix_height(*node);
        const int balance = balance_of(*node);
        if (balance > 1) {  // left-heavy
            if (balance_of(*node->left) < 0) node->left = rotate_left(std::move(node->left));  // LR: straighten the zig-zag first
            return rotate_right(std::move(node));  // LL (or the second half of LR)
        }
        if (balance < -1) {  // right-heavy
            if (balance_of(*node->right) > 0) node->right = rotate_right(std::move(node->right));  // RL: straighten the zig-zag first
            return rotate_left(std::move(node));  // RR (or the second half of RL)
        }
        return node;
    }
 
    Ptr rotate_right(Ptr down) {
        Ptr up = std::move(down->left);
        down->left = std::move(up->right);  // the middle subtree changes parent
        fix_height(*down);
        up->right = std::move(down);
        fix_height(*up);
        ++rotations_;
        return up;
    }
 
    Ptr rotate_left(Ptr down) {
        Ptr up = std::move(down->right);
        down->right = std::move(up->left);
        fix_height(*down);
        up->left = std::move(down);
        fix_height(*up);
        ++rotations_;
        return up;
    }
 
    // The verified height of the subtree, or nullopt when something is broken.
    static std::optional<int> verify(const Node* node, std::optional<int> low, std::optional<int> high) {
        if (node == nullptr) return -1;
        if ((low && node->key <= *low) || (high && node->key >= *high)) return std::nullopt;
        const auto left = verify(node->left.get(), low, node->key);
        if (!left) return std::nullopt;
        const auto right = verify(node->right.get(), node->key, high);
        if (!right) return std::nullopt;
        const bool ok = node->height == 1 + std::max(*left, *right) && std::abs(*left - *right) <= 1;
        return ok ? std::optional<int>(node->height) : std::nullopt;
    }
 
    static void walk(const Node* node, std::vector<int>& keys, bool pre) {
        if (node == nullptr) return;
        if (pre) keys.push_back(node->key);
        walk(node->left.get(), keys, pre);
        if (!pre) keys.push_back(node->key);
        walk(node->right.get(), keys, pre);
    }
 
    Ptr root_;
    std::size_t count_ = 0;
    int rotations_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/avl_tree.hpp

References