Data Structures · Visualization
AVL Tree: Introduction
AVL Tree
An AVL tree is a binary search tree that automatically keeps itself balanced. Time: O(log n) guaranteed for search, insert, and delete. Space: O(n).
Big-O: Every operation stays O(log n) thanks to rotations.
AVL Tree: Introduction
AVL TreeAn AVL tree is a binary search tree that automatically keeps itself balanced. After every insert or delete, it checks a 'balance factor' at each node (the height of the left subtree minus the height of the right subtree). If that factor ever becomes -2 or +2, the tree performs a 'rotation' — a local rearrangement of a few nodes — to restore balance. This guarantees the tree's height always stays close to log(n), so operations never degrade to the slow O(n) worst case a plain BST can suffer from.
How AVL Tree: Introduction Works
- Follow all the normal BST ordering rules (left is smaller, right is larger).
- After every insert or delete, walk back up from the changed node to the root, updating heights.
- At each node, compute the balance factor: height(left subtree) - height(right subtree).
- If the balance factor is +2 or -2, apply the appropriate rotation (left, right, left-right, or right-left) to fix it.
AVL Tree: Introduction Worked Example
Input: Insert 30, 20, 10 one by one
- Insert 30: tree is just [30], balanced
- Insert 20: 20 < 30, becomes left child. Balanced (factor 1)
- Insert 10: 10 < 30, 10 < 20, becomes left-left. Balance factor at 30 becomes +2 → unbalanced!
- A single right rotation at 30 fixes it, making 20 the new root
Output: 20 / \ 10 30
Press ▶ Run to watch it step by step.
class AVLNode:
def __init__(self, key):
self.key = key
self.left = self.right = None
self.height = 1 # height of the subtree
def height(n):
return n.height if n else 0
def balance(n): # balance factor
return height(n.left) - height(n.right) # must be in {-1, 0, 1}
# example: introAVL Tree: Introduction Time & Space Complexity
When to Use AVL Tree: Introduction
- Databases and in-memory indexes needing guaranteed fast lookups
- Situations with frequent insertions/deletions where worst-case performance matters
- Any use case where a plain BST risks becoming a lopsided, slow chain
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.