Trees · O(log n) search and insert
AVL tree
Insert into a self-balancing BST with LL, RR, LR and RL rotations and balance factors.
The full explanation, derivation and practice are in the lesson AVL trees and rotations, with red-black trees and B-trees.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
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<T> / SortedDictionary<TKey,TValue>
/// (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