Oh My Algorithm
Algorithm Guidecomplexity: O(log n)

AVL Tree

A self-balancing binary search tree that keeps the height difference of every node's left and right subtrees at most 1. After an insert or delete it restores balance with rotations, guaranteeing O(log n) at all times.

01AVL Tree

AVL tree. A self-balancing BST that restores balance with rotations whenever the left/right height difference exceeds 1 after an insert.

insert(20) · 20 > 10, so attach it as the right child. Still balanced.

insert(30) · it all leans right into a 10→20→30 chain. Node 10's balance factor is -2 — unbalanced!

Rotate left · pull the middle node 20 up and drop 10 to its left child.

Balance restored · height drops from 2 to 1. Keeping balance every time guarantees O(log n).

10
1 / 5

02 Understand It Simply

For Everyone
🔑How It Works

Keeps the height difference between a node's subtrees within one, restoring it by rotation whenever it slips, which bounds the height at O(log n).

💡In Plain Words

A BST that restores balance with a 'rotation' whenever the left/right height difference exceeds 1 after an insert or delete.

That guarantees O(log n) instead of degrading to a lopsided, slow tree.

📍Where It's Used
  • Sorted data that needs frequent search
  • database indexes

03 Python Implementation

A clean, readable reference implementation of the core logic of AVL Tree.

core_implementation.py
def height(n):
    return n.height if n else 0

def balance(n):
    return height(n.left) - height(n.right) if n else 0

def rotate_right(y):
    x = y.left
    y.left = x.right
    x.right = y
    update(y); update(x)
    return x

def insert(node, key):
    if not node:
        return Node(key)
    if key < node.key:
        node.left = insert(node.left, key)
    else:
        node.right = insert(node.right, key)
    update(node)
    return rebalance(node)  # rotate if |balance| > 1

04 Frequently Asked Questions

FAQ
What is AVL Tree?+

A self-balancing binary search tree that keeps the height difference of every node's left and right subtrees at most 1. After an insert or delete it restores balance with rotations, guaranteeing O(log n) at all times.

What is the time complexity of AVL Tree?+

The time complexity of AVL Tree is O(log n). Follow the step-by-step visualization to see exactly why.

Where is AVL Tree used?+

Sorted data that needs frequent search, database indexes.

What's a simple analogy for AVL Tree?+

Keeps the height difference between a node's subtrees within one, restoring it by rotation whenever it slips, which bounds the height at O(log n).