Why balance matters
32 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Self-balancing binary search trees maintain logarithmic height through tree rotations during modifications.
The cost of skewed trees and the rotation idea
A balanced tree keeps its height close to log n, so search, insert and delete stay O(log n) instead of becoming O(n) like a long chain.
A BST that receives keys in sorted order becomes a chain, so every operation costs O(n). A rotation changes the shape without changing the inorder order, which brings the height back down.
Example 1 · Right and Left Rotations
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static TreeNode rotateRight(TreeNode y) { TreeNode x = y.left; TreeNode t2 = x.right; x.right = y; y.left = t2; return x; }
static TreeNode rotateLeft(TreeNode x) { TreeNode y = x.right; TreeNode t2 = y.left; y.left = x; x.right = t2; return y; }
public static void main(String[] args) { TreeNode y = new TreeNode(30); y.left = new TreeNode(20); y.left.left = new TreeNode(10);
TreeNode newRoot = rotateRight(y); System.out.println("Root after right rotation: " + newRoot.val); System.out.println("Left child: " + newRoot.left.val); System.out.println("Right child: " + newRoot.right.val); }}Root after right rotation: 20 Left child: 10 Right child: 30
What this code does
- Right rotation elevates the left child into the new subtree root.
- The middle subtree reattaches cleanly to preserve BST ordering.
- Subtree height decreases by one without changing inorder sequence.
A binary search tree performs best when heights of left and right subtrees stay nearly equal. If keys arrive in ascending order, each node attaches as a right child. This creates a degenerate skewed tree resembling a linked list. Operations that should run in logarithmic time degrade to O(n) linear scans.
Tree rotations restructure nodes without altering the inorder traversal order. A right rotation raises the left child and lowers the parent. A left rotation raises the right child and lowers the parent. Because BST ordering rules remain intact, rotations safely reduce subtree heights.
AVL and red-black trees at a glance
Self-balancing trees automatically perform rotations during insertions and deletions. An AVL tree strictly enforces that child subtree heights differ by at most one. This strict balance guarantees very fast lookups at the cost of more frequent rotations.
Example 2 · Checking the AVL Balance Factor
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static int height(TreeNode node) { if (node == null) return 0; return 1 + Math.max(height(node.left), height(node.right)); }
static int getBalance(TreeNode node) { if (node == null) return 0; return height(node.left) - height(node.right); }
public static void main(String[] args) { TreeNode balanced = new TreeNode(10); balanced.left = new TreeNode(5); balanced.right = new TreeNode(15);
TreeNode skewed = new TreeNode(10); skewed.right = new TreeNode(15); skewed.right.right = new TreeNode(20);
System.out.println("Balanced factor: " + getBalance(balanced)); System.out.println("Skewed factor: " + getBalance(skewed)); }}Balanced factor: 0 Skewed factor: -2
What this code does
- Balance factor equals left child height minus right child height.
- Valid AVL nodes must maintain a balance factor of -1, 0, or 1.
- A balance factor of -2 triggers a rebalancing rotation sequence.
A red-black tree colors every node either red or black. It enforces balancing rules using node colors and black-height properties. No path from root to leaf is more than twice as long as any other path. This looser balance requires fewer rotation adjustments during insertions and deletions.
TreeMap and TreeSet in the Java standard library
The Java standard library uses red-black trees to power TreeMap and TreeSet. Keys remain sorted at all times according to natural ordering or a custom comparator.
Example 3 · TreeMap Logarithmic Guarantees
import java.util.TreeMap;
public class Main { public static void main(String[] args) { TreeMap<Integer, String> map = new TreeMap<>(); map.put(50, "Root"); map.put(20, "Left"); map.put(80, "Right"); map.put(10, "Left-Left");
System.out.println("First key: " + map.firstKey()); System.out.println("Last key: " + map.lastKey()); System.out.println("Floor of 40: " + map.floorKey(40)); System.out.println("Ceiling of 40: " + map.ceilingKey(40)); }}First key: 10 Last key: 80 Floor of 40: 20 Ceiling of 40: 50
What this code does
- TreeMap maintains key sorted order internally using Red-Black trees.
- Navigation operations run in guaranteed O(log n) time.
- Floor and ceiling provide nearest neighbor boundary lookups.
Operations including containsKey, get, put, and remove run in guaranteed O(log n) time. Unlike HashMaps, TreeMaps support range navigation methods like subMap, floorKey, and ceilingKey. Choosing between hashing and balanced trees depends on whether sorted order is required.
Next step
Check your understanding
10 quick questions