Sub topic 3
Rotations: Changing Shape Without Breaking Order
Prerequisites
This chapter assumes you can read Python and follow recursive code. It also assumes you know the binary search tree (BST) ordering rule: for every node, all keys in its left subtree are smaller and all keys in its right subtree are larger. You should know that the height of a tree is the number of nodes on its longest root-to-leaf path. This tutorial counts an empty tree as height 0 and a single node as height 1.
The problem rotations solve
A BST gets slow when it gets tall. Inserting 1, 2, 3, 4, 5 in order gives a chain, and every search walks the whole chain. To fix this, a balanced tree needs a way to reshape itself after an insertion or deletion. The reshaping must meet two conditions:
- It must keep the BST ordering rule true.
- It must be cheap, ideally constant time, so repairs do not cost more than the operation that caused them.
A rotation meets both conditions. It is a local rearrangement of two nodes, a parent and one of its children, that changes which of them is higher in the tree. Both AVL trees and red-black trees use rotations as their only structural repair tool.
Right rotation
Take a node y with a left child x. Call the three subtrees hanging off them A, B and C:
Ais the left subtree ofx.Bis the right subtree ofx.Cis the right subtree ofy.
A right rotation at y lifts x into y's place and pushes y down to the right.
Only three links change:
y.leftwasx. It becomesB, the old right subtree ofx.x.rightwasB. It becomesy.- Whoever pointed at
ynow points atx.
Subtrees A and C keep their parents. Every key inside every subtree stays where it was relative to its own subtree.
Why the ordering survives
The BST rule gives the following inequality, where each letter stands for all keys in that subtree:
A < x < B < y < C
Every key in A is less than x. Every key in B is greater than x, because B is in x's right subtree. Every key in B is also less than y, because x is in y's left subtree. Every key in C is greater than y.
Now read the tree after the rotation. x has A on the left, so A < x. x has y's subtree on the right, and that subtree holds B, y and C, all greater than x. y has B on the left, so B < y, and C on the right, so y < C. The rule holds at both nodes.
Both shapes also have the same in-order traversal: A, x, B, y, C. This gives you a simple correctness test. Rotation must never change the in-order sequence.
Left rotation
A left rotation is the mirror image. Take a node x with a right child y. The subtrees are A (left of x), B (left of y) and C (right of y). The rotation lifts y and pushes x down to the left. The two rotations undo each other: rotate_left(rotate_right(y)) restores the original shape.
The direction names describe the direction the demoted node moves. In a right rotation, y moves down and to the right.
| Operation | Pivot (node you call it on) | Child that moves up | Subtree that changes parent |
|---|---|---|---|
| Right rotation | `y` | `y.left` | right subtree of the promoted child |
| Left rotation | `x` | `x.right` | left subtree of the promoted child |
The code
The nodes store their height, so a rotation must refresh the two heights that changed. The order of the updates matters. y is now the child, so update it first. Then update x, whose height depends on y's.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1 # height of a single node is 1; empty tree is 0
def height(n):
return n.height if n else 0
def update(n):
n.height = 1 + max(height(n.left), height(n.right))
def rotate_right(y):
x = y.left
y.left = x.right
x.right = y
update(y)
update(x)
return x
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
update(x)
update(y)
return y
def in_order(n):
if n is None:
return []
return in_order(n.left) + [n.key] + in_order(n.right)
def build():
y = Node(30)
x = Node(20)
x.left = Node(10)
x.right = Node(25)
y.left = x
y.right = Node(40)
update(x)
update(y)
return y
root = build()
print(in_order(root), root.key, root.height)
root = rotate_right(root)
print(in_order(root), root.key, root.height)
root = rotate_left(root)
print(in_order(root), root.key, root.height)The output is:
[10, 20, 25, 30, 40] 30 3
[10, 20, 25, 30, 40] 20 3
[10, 20, 25, 30, 40] 30 3The in-order list is identical in all three lines, and the root changes from 30 to 20 and back. Notice that subtree B (the node 25) moved from being a child of 20 to being a child of 30 and back.
Returning the new root
Each function returns the new subtree root instead of modifying the tree in place. The caller must store that value. If you call rotate_right(y) and ignore the result, the parent of y still points at y, and x and everything above it become unreachable from the parent. The usual pattern when rotating a node that has a parent is:
parent.left = rotate_right(parent.left)Recursive insertion and deletion code gets this for free, because each recursive call already returns the subtree root to its caller and the caller assigns it back. You will see this in the AVL chapters.
Cost and effect on heights
A rotation does a fixed number of pointer assignments and two height updates, so it runs in O(1) time. It changes the heights of only x and y. A rotation can change the height of the whole subtree, though. In the example above the subtree height stayed at 3, but if A had been tall and C short, a right rotation would lower the subtree's height by one. Balanced-tree algorithms exploit this. A rotation at an overloaded node can reduce the height of its subtree, and that restores balance higher up.
Edge cases and common errors
- Missing child.
rotate_right(y)needsy.leftto exist. If it isNone,x.rightraisesAttributeError. The balancing algorithms only rotate when the heavy side is known to be non-empty, but your own code should check. - Wrong update order. Updating
xbeforeycomputesx's height fromy's stale height. The tree then stores a wrong height that no later check will notice until a balance decision goes wrong. - Forgetting to reattach. As noted above, the result must be stored in the parent link or in
root. - Parent pointers. The code here has no parent pointers. If your nodes have them, a rotation must also fix three of them: the parent of the promoted node, the parent of the demoted node, and the parent of the moved subtree
B(if it is not empty). - Duplicates. The inequality
A < x < B < y < Cassumes distinct keys. If your tree allows equal keys, you must pick a side for them and make sure rotations keep that choice consistent.
Testing a rotation
Because rotation promises to preserve order, two quick checks catch most bugs:
- Compare
in_orderbefore and after. They must match. - Recompute each stored height from the children and compare it to the cached value.
You will see this idea again in the chapter on testing tree invariants.
Exercise
In a right rotation at y with left child x, which subtree changes parent, and what are its old and new parents?
Show answer
The right subtree of x (called B). Its old parent is x, where it was the right child. Its new parent is y, where it becomes the left child. Its keys are greater than x and less than y, so they fit in y's left slot.
Exercise
A tree has root 10 with only a right child 20, and 20 has only a right child 30. Apply one left rotation at 10. What are the new root, its children, and the new height? Does the in-order sequence change?
Show answer
The new root is 20, with left child 10 and right child 30. The height is 2, down from 3. The in-order sequence is 10, 20, 30 before and after. Here the moved subtree B is empty, so 10's right link becomes empty.