Advanced data structuresAnimated
AVL Tree
A BST that rotates to keep child heights within 1.
Time
O(log n)
Extra space
O(n)
Use it for
Lookup-heavy ordered data.
How it works
- An AVL tree is a binary search tree that keeps itself balanced: at every node the heights of the left and right subtrees differ by at most 1. That guarantees O(log n) search, insert and delete.
- Insert like in any BST: smaller goes left, larger goes right.
- Then walk back up, updating heights. The first node whose balance factor (left height − right height) becomes +2 or −2 is out of balance.
- Fix it with rotations. A straight line (left-left or right-right) needs one rotation. A zig-zag (left-right or right-left) needs two. After one fix the whole tree is balanced again.
Watch it run
Loading animation…