No history yet

Self Balancing Trees

The Unbalanced Tree Problem

A standard Binary Search Tree (BST) offers fantastic performance, but only under the right conditions. Searching for an item typically takes O(logn)O(\log n) time because each comparison cuts the search space in half. This efficiency hinges on the tree being reasonably balanced, with nodes distributed evenly between the left and right subtrees.

But what happens if you insert data that's already sorted? If you add the numbers 1, 2, 3, 4, and 5 in that order, the BST doesn't form a bushy, balanced shape. Instead, it becomes a long, spindly chain where every node is a right child of the previous one. This structure is essentially a linked list. A search operation degrades to O(n)O(n) time, as you have to check every single node in the worst case. The tree's primary advantage is lost.

To solve this, computer scientists developed self-balancing binary search trees. These data structures automatically adjust their shape after every insertion or deletion to ensure the tree remains balanced, preserving that coveted O(logn)O(\log n) performance. We'll look at two popular types: AVL trees and Red-Black trees.

AVL Trees

Named after its inventors, Adelson-Velsky and Landis, the AVL tree was the first self-balancing BST. It maintains balance by enforcing a strict rule: for every node, the height of its left and right subtrees can differ by at most one. This property is tracked using a "balance factor."

Balance Factor

noun

The height of the right subtree minus the height of the left subtree. For an AVL tree, this value must be -1, 0, or 1 for every node.

When an insertion or deletion violates this rule and causes a node's balance factor to become -2 or 2, the tree performs one or more "rotations" to restore balance. A rotation is a local transformation that rearranges nodes while preserving the BST property (left child < parent < right child).

Think of it like re-stacking a pile of books. If one side gets too high, you shift a few books from the top to even things out without changing their overall order.

There are four types of rotations to handle different imbalance scenarios:

  • Left Rotation: Used when a node is right-heavy, and its right child is also right-heavy or balanced.
  • Right Rotation: Used when a node is left-heavy, and its left child is also left-heavy or balanced.
  • Left-Right Rotation: A combination of a left rotation followed by a right rotation. It handles cases where a node is left-heavy, but its left child is right-heavy.
  • Right-Left Rotation: A right rotation followed by a left rotation. It fixes imbalances where a node is right-heavy, but its right child is left-heavy.

Because AVL trees are so strictly balanced, lookup operations are extremely fast. However, this rigid structure means they may require more rotations during insertions and deletions, making them slightly slower for applications with frequent writes.

Use AVL Trees when your application involves frequent lookups and infrequent insertions or deletions.

Red-Black Trees

A Red-Black tree is another type of self-balancing BST that offers a different trade-off. It uses a cleverer, more relaxed set of rules to maintain balance, which often results in fewer rotations for insertions and deletions compared to an AVL tree. Instead of a balance factor, each node is assigned a color, either red or black.

This coloring must follow a specific set of properties:

  1. Every node is either red or black.
  2. The root node is always black.
  3. All leaves (NIL nodes) are black.
  4. If a node is red, then both its children are black.
  5. Every simple path from a given node to any of its descendant leaves contains the same number of black nodes.
Lesson image

The fifth rule, known as the "black-height" property, is the key to keeping the tree balanced. It ensures that the longest path from the root to a leaf is no more than twice as long as the shortest path. This guarantees a height of approximately O(logn)O(\log n). When an insertion or deletion violates these rules, the tree uses rotations and color flips to restore the properties.

Use Red-Black Trees when your application involves frequent insertions and deletions along with lookups.

Because their balancing rules are less strict, Red-Black trees might be slightly less balanced than AVL trees, leading to marginally slower lookups on average. However, they shine in write-heavy scenarios because insertions and deletions require at most two rotations, making them faster to modify.

Choosing the Right Tree

So, which one should you use? The choice depends entirely on your application's workload.

FeatureAVL TreeRed-Black Tree
BalanceMore strictly balancedLess strictly balanced
Lookup SpeedFasterSlightly slower
Insertion/Deletion SpeedSlower (more rotations)Faster (fewer rotations)
Common Use CasesDatabases where reads are far more common than writes.Language libraries (e.g., C++ map, Java TreeMap), process schedulers.

Both AVL and Red-Black trees solve the problem of BST degradation by guaranteeing logarithmic time complexity for core operations. By understanding their different balancing strategies, you can choose the right tool for the job and build highly efficient systems.

Ready to test your knowledge?

Quiz Questions 1/6

What is the primary problem with a standard Binary Search Tree (BST) that self-balancing trees like AVL and Red-Black trees are designed to solve?

Quiz Questions 2/6

An AVL tree uses a "balance factor" to maintain its structure. An imbalance occurs, triggering rotations, when a node's balance factor becomes...

By automatically rebalancing, these advanced trees ensure that performance remains predictable and efficient, even when handling dynamic data.