Data Structures & Algorithms / Module 6: Trees

Topic 6.3

Unbalanced trees

Sorted data turns a BST into a chain; balanced trees fix that with rotations.

9 min · advanced

Watch: the same numbers, added in a different order, make either a bushy tree or one long straight line.

  • moving now
Step 1 of 9

Insert 4, 2, 6, 1, 3, 5, 7 one by one into an empty BST.

A plain BST doesn't manage its own shape. The order data arrives in decides its height, and the height decides how fast a search is.

Why sorted data breaks the tree

Insert 1, then 2. Since 2 is bigger, it becomes the right child. Then 3, bigger than both, so it's 2's right child. Every new number is the biggest so far, so it always goes right. The result isn't a branching tree but a chain. Finding 7 means walking all seven nodes, just like a linked list.

This isn't a rare case. Auto-incrementing IDs, timestamps and order numbers all arrive in ascending order. A plain BST filled with data like that always turns into a chain.

Trees that keep their shape

The fix: after inserting, check whether one side has become too tall compared with the other. If so, do a rotation: lift a child up to be the parent, and make the old parent its child. The BST rule (small left, big right) still holds, but the height goes down.

  • AVL tree: at every node, the left and right heights differ by at most 1. Very tidy, fast to read.
  • Red-black tree: looser rules, so fewer rotations on insert. Used in Java's TreeMap, C++'s std::map and the Linux process scheduler.

Both guarantee the height stays around log n, whatever order the data comes in.

Code, for programmersA left rotation: 1-2-3 becomes 2 with children 1 and 3
//   1                 2
//    \               / \
//     2      ->     1   3
//      \
//       3
function rotateLeft(x) {
  const y = x.right;
  x.right = y.left;   // y's left subtree is bigger than x, so it moves under x
  y.left = x;
  return y;           // y is the new root of this part
}

Quiz

  1. Insert 10, 20, 30, 40, 50 into an empty plain BST. How tall is it?

  2. What does a rotation do?

  3. Which data is riskiest for an unbalanced BST?

0 of 3 answered.