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.
Watch: the same numbers, added in a different order, make either a bushy tree or one long straight line.
- moving now
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
Insert 10, 20, 30, 40, 50 into an empty plain BST. How tall is it?
What does a rotation do?
Which data is riskiest for an unbalanced BST?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.