Skip to content
Visual explainer 3h to learn 5 steps

Balanced trees: AVL & red-black concepts

Explain how rotations keep AVL and red-black trees at O(log n) height.

By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.

Topic 27 of 54

In short

Self-balancing trees restructure themselves with rotations after inserts and deletes so height stays O(log n). AVL trees keep subtree heights within one of each other, while red-black trees use colouring rules that allow a little more imbalance in exchange for fewer rotations. They back ordered maps in many standard libraries.

Explained simply

A plain binary search tree can turn into a long chain if keys arrive in a bad order, and then it is as slow as a list. A balanced tree checks itself after every insert and delete. If one side has become too tall, it rearranges a few nodes to even things out.

The rearranging move is called a rotation. Picture a mobile hanging from the ceiling: if it tilts to the left, you lift the left arm up to be the new top and let the old top swing down to the right. Only a few pointers change, and the sorted order of the keys stays exactly the same.

Two famous designs use rotations. AVL trees are strict: at every node, the heights of the left and right subtrees may differ by at most one. Red-black trees colour each node red or black and follow a few colour rules, which allow a bit more imbalance but need fewer fixes.

Either way, the height stays around log n. So search, insert and delete are guaranteed O(log n), even if keys come in sorted order. These trees power ordered maps in Java, C++ and the Linux kernel.

Press Play on a diagram to walk through it one step at a time.

CompareAVL versus red-black
AVL
  • Balance factor in -1, 0, 1
  • Height about 1.44 log n
  • Faster lookups
  • More rotations on updates
Red-black
  • Nodes coloured red or black
  • Height at most 2 log(n+1)
  • At most 2-3 rotations per insert or delete
  • Used by Java TreeMap and C++ std::map
FlowInserting 1, 2, 3 into an AVL tree
  1. 1
    Insert 1

    Single node, balance 0.

  2. 2
    Insert 2

    Right child of 1; balance at 1 is -1.

  3. 3
    Insert 3

    Right of 2; balance at 1 becomes -2.

  4. 4
    Case RR

    Rotate left at 1.

  5. 5
    Result

    2 is root with children 1 and 3, height 1.

In depth

Rotations: the one operation that rebalances

A right rotation at node y with left child x makes x the new subtree root, y becomes x's right child, and x's old right subtree (call it B) becomes y's new left subtree. In sorted order, the keys are A < x < B < y < C both before and after, so the BST rule still holds. A left rotation is the mirror image.

A rotation changes only three pointers (plus the link from the parent), so it costs O(1). Its effect on heights is what matters: the left side loses one level and the right side gains one. After a rotation you recompute the stored heights of y first (it is now lower), then x.

Some imbalances need two rotations. If the left child is itself right-heavy (a zigzag shape), one right rotation would just make a mirror zigzag. Rotate the child left first to straighten the path, then rotate the node right. This is called a double rotation.

  • O(1) work, in-order sequence unchanged
  • Update heights bottom-up: old root first, new root second
  • Zigzag shapes need a double rotation
CompareRight rotation at y
Before
  • y is the subtree root
  • x is y's left child
  • x has subtrees A and B
  • y's right subtree is C
After
  • x is the subtree root
  • y is x's right child
  • x keeps A on the left
  • y gets B on the left, keeps C

AVL trees: balance factors and the four cases

Every AVL node stores its height. The balance factor is height(left) - height(right) and must stay in -1, 0 or 1. After inserting a leaf, walk back up the path, updating heights. The first node whose balance factor becomes 2 or -2 needs fixing.

There are four cases, named by the path from that node to the inserted key. LL (left child, then its left): one right rotation. RR: one left rotation. LR (left child, then its right): rotate the child left, then the node right. RL: the mirror.

On insert, one single or double rotation always fixes the whole tree, because it restores the subtree's height to what it was before the insert. On delete, a rotation may shorten the subtree, so imbalance can move upward and up to O(log n) rotations may be needed.

AVL trees are very tightly balanced: height is less than about 1.44 log2(n + 2). That makes lookups slightly faster than in red-black trees.

MapAVL imbalance cases at node z
z has balance factor +2 or -2
  • LL
    • New key in left of left
    • Fix: rotate z right
  • RR
    • New key in right of right
    • Fix: rotate z left
  • LR
    • New key in right of left
    • Fix: rotate child left, then z right
  • RL
    • New key in left of right
    • Fix: rotate child right, then z left

Red-black trees: the rules and why they work

Each node is red or black, and empty child slots (None) count as black leaves. The rules: the root is black; a red node never has a red child; and every path from a node down to an empty leaf has the same number of black nodes, called the black height.

Why does this bound the height? The shortest possible root-to-leaf path is all black. The longest alternates red and black, because two reds cannot be adjacent. So no path is more than twice as long as another, which gives height at most 2 log2(n + 1).

Insert colours the new node red (which keeps black heights equal) and then fixes any red-red violation by recolouring or rotating. Recolouring can push the problem up the tree, but insert needs at most 2 rotations and delete at most 3. Fewer structural changes make red-black trees a popular choice when writes are frequent.

  • Root black, no red-red parent and child, equal black height
  • Height at most 2 log2(n + 1)
  • At most 2 rotations per insert, 3 per delete

Where balanced trees appear, and Python options

Java's TreeMap and TreeSet are red-black trees, offering floorKey, ceilingKey and subMap range views. C++ std::map and std::set are typically red-black trees. The Linux kernel has a widely used red-black tree library, used for example by its process scheduler and memory management.

Databases and file systems mostly use B-trees and B+ trees instead. These are balanced trees with hundreds of keys per node, so a lookup touches only 3 or 4 disk pages even for billions of rows. Redis sorted sets use a skip list, a randomised structure with the same expected O(log n) costs.

Python's standard library has no balanced tree. For sorted data with updates, the third-party sortedcontainers package (SortedList, SortedDict) is the usual answer; it stores a list of sorted sublists and is fast in practice. For read-mostly data, a sorted list plus bisect is often enough.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Perform left and right rotations~35m
  2. 2
    Track AVL balance factors~35m
  3. 3
    State the red-black tree rules~35m
  4. 4
    Compare AVL and red-black trade-offs~35m
  5. 5
    Know where balanced trees appear in libraries~35m

Key points

  • Search, insert and delete: O(log n) worst case.
  • A rotation is O(1) and preserves in-order order.
  • AVL fixes four cases: LL, RR, LR and RL.
  • Python has no built-in balanced BST; use sortedcontainers or bisect on lists.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def height(n):
    return n.h if n else 0

def rotate_right(y):              # O(1)
    x = y.left
    y.left, x.right = x.right, y
    y.h = 1 + max(height(y.left), height(y.right))
    x.h = 1 + max(height(x.left), height(x.right))
    return x                      # new subtree root

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

AVL insert calls rotations when balance(n) leaves the range -1 to 1.

A complete AVL insert

Each node stores its height. After recursive insertion, we update the height and compute the balance. If it is +2 the left side is too tall: an LR shape is first straightened by rotating the child left. If it is -2, the mirror. Inserting 1 to 7 in sorted order, which would make a chain in a plain BST, yields a perfect tree of height 3 (counting nodes) with 4 at the root.

python
class N:
    def __init__(s, k): s.k, s.l, s.r, s.h = k, None, None, 1
h = lambda n: n.h if n else 0
def fix(n): n.h = 1 + max(h(n.l), h(n.r)); return n
def rot_r(y): x = y.l; y.l, x.r = x.r, y; fix(y); return fix(x)
def rot_l(x): y = x.r; x.r, y.l = y.l, x; fix(x); return fix(y)
def insert(n, k):
    if not n: return N(k)
    if k < n.k: n.l = insert(n.l, k)
    else: n.r = insert(n.r, k)
    b = h(fix(n).l) - h(n.r)
    if b > 1:
        if k > n.l.k: n.l = rot_l(n.l)          # LR
        return rot_r(n)
    if b < -1:
        if k < n.r.k: n.r = rot_r(n.r)          # RL
        return rot_l(n)
    return n

Ordered-map queries with a sorted list

Python has no TreeMap, but floor and ceiling queries are easy with bisect on a sorted list. Here a list of price levels answers "highest price at or below 105" and "lowest price at or above 105". Lookups are O(log n); inserting with insort is O(n) because of shifting, which is fine for thousands of items. For heavy updates, sortedcontainers.SortedList gives the same API with fast inserts.

python
from bisect import bisect_left, bisect_right, insort

prices = [90, 100, 110, 120]
insort(prices, 104)                      # [90, 100, 104, 110, 120]

def floor_key(a, x):
    i = bisect_right(a, x)
    return a[i - 1] if i else None

def ceiling_key(a, x):
    i = bisect_left(a, x)
    return a[i] if i < len(a) else None

print(floor_key(prices, 105), ceiling_key(prices, 105))  # 104 110

Quick reference

  • Rotation: O(1), keeps in-order order, moves one level of height between sides
  • AVL: balance factor in {-1, 0, 1}; height < about 1.44 log2(n + 2)
  • AVL cases: LL rotate right, RR rotate left, LR left-then-right, RL right-then-left
  • AVL insert: at most one single or double rotation; delete: up to O(log n)
  • Red-black: root black, no red-red, equal black height; height <= 2 log2(n + 1)
  • Red-black: at most 2 rotations per insert, 3 per delete
  • Java TreeMap and C++ std::map use red-black trees; databases use B+ trees

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1An AVL node has balance factor +2 and the new key went into its left child's right subtree. Which fix applies?

Question 2

2What is the maximum height of a red-black tree with n keys?

Question 3

3Which statement about rotations is true?

Question 4

4Why do new red-black tree nodes start red?

Question 5

5Which data structure do relational databases typically use for indexes?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Using N, fix, rot_l and rot_r from the AVL example, build the chain 1 -> 2 -> 3 (each a right child), apply one rotation to balance it, and print the new root and its children. Expected: 2 1 3.

  2. Exercise 2medium

    Write is_avl(root) for the N class that checks the AVL balance rule at every node in O(n) without trusting the stored h values. Return True or False.

  3. Exercise 3hard

    Insert the keys 1 to 2**k - 1 in sorted order into the AVL tree for k = 10 and confirm the tree height (in nodes) is exactly k. Then compare with a plain BST, where the height would be 2**k - 1.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use AVL or red-black trees?
AVL trees are more tightly balanced, so lookups are slightly faster. Red-black trees do fewer rotations on updates, which is why most standard libraries use them. In practice you use the library's tree rather than writing your own.
Do I need to implement red-black deletion for interviews?
Almost never. Knowing the rules, the height bound, rotations and when balanced trees are needed is usually enough; AVL insertion is the most common one asked to code.
What should I use in Python instead of a TreeMap?
The sortedcontainers package (SortedDict, SortedList) for frequent updates, or a sorted list with bisect for mostly read-only data. heapq works if you only need the minimum.

Go deeper

ShareXLinkedInWhatsApp