Rotations
Balanced trees repair themselves with one local operation, the rotation. A rotation changes the shape of the tree around one edge, moving one subtree up a level and another down, while keeping the BST property. It changes a constant number of pointers, so it takes time, and red-black insertion and deletion use at most two and three of them respectively.
Left and right rotation
A left rotation at node needs 's right child to be an internal node. It makes the new root of the subtree, becomes 's left child, and 's former left subtree moves over to become 's right subtree. A right rotation at undoes it.
x y
/ \ LEFT-ROTATE(x) / \
α y -------------> x γ
/ \ <------------- / \
β γ RIGHT-ROTATE(y) α βThe inorder sequence is on both sides: every key of is less than , every key of is between and , and every key of is greater than . So a rotation preserves the BST property. Depths change only for the moved parts: goes one level down, one level up, and stays at the same depth.
LEFT-ROTATE(T, x)
1 y = x.right
2 x.right = y.left // β becomes x's right subtree
3 if y.left != T.nil
4 y.left.parent = x
5 y.parent = x.parent // y takes x's place under x's parent
6 if x.parent == T.nil
7 T.root = y
8 elseif x == x.parent.left
9 x.parent.left = y
10 else x.parent.right = y
11 y.left = x // x goes under y
12 x.parent = yRIGHT-ROTATE is the same with left and right exchanged. Six pointers change: the two links between and , the link to (both directions) and the link from the parent (both directions).
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right, self.parent = key, left, right, None
for c in (left, right):
if c: c.parent = self
class Tree:
def __init__(self, root):
self.root = root
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left: y.left.parent = x
y.parent = x.parent
if x.parent is None: self.root = y
elif x is x.parent.left: x.parent.left = y
else: x.parent.right = y
y.left, x.parent = x, y
def right_rotate(self, y):
x = y.left
y.left = x.right
if x.right: x.right.parent = y
x.parent = y.parent
if y.parent is None: self.root = x
elif y is y.parent.right: y.parent.right = x
else: y.parent.left = x
x.right, y.parent = y, x
def show(x):
"""parenthesised form: key(left, right), '-' for an empty subtree"""
if x is None: return "-"
if x.left is None and x.right is None: return str(x.key)
return f"{x.key}({show(x.left)}, {show(x.right)})"
def inorder(x):
return [] if x is None else inorder(x.left) + [x.key] + inorder(x.right)
# x = 10 with alpha = 5, y = 20 with beta = 15 and gamma = 30(25, 40)
t = Tree(Node(10, Node(5), Node(20, Node(15), Node(30, Node(25), Node(40)))))
print("start: ", show(t.root), inorder(t.root))
t.left_rotate(t.root)
print("left-rotate at 10: ", show(t.root), inorder(t.root))
t.left_rotate(t.root)
print("left-rotate at 20: ", show(t.root), inorder(t.root))
t.right_rotate(t.root)
t.right_rotate(t.root)
print("two right rotations:", show(t.root), inorder(t.root))start: 10(5, 20(15, 30(25, 40))) [5, 10, 15, 20, 25, 30, 40]
left-rotate at 10: 20(10(5, 15), 30(25, 40)) [5, 10, 15, 20, 25, 30, 40]
left-rotate at 20: 30(20(10(5, 15), 25), 40) [5, 10, 15, 20, 25, 30, 40]
two right rotations: 10(5, 20(15, 30(25, 40))) [5, 10, 15, 20, 25, 30, 40]
Each rotation moved one node up to the root; the inorder sequence never changed. Two right rotations restored the starting tree exactly.
Rotations can reach every shape
Any BST on a set of keys can be turned into any other BST on the same keys by rotations alone, and of them suffice. The reason: right rotations at the root's left child pull nodes onto the right spine, and at most of them turn any tree into a right-going chain (a path through the right pointers in sorted order). Since rotations are reversible, going from tree to the chain and then backwards from the chain to tree takes at most rotations.
The program turns random BSTs and a left-going path into the chain, counts the rotations and checks the order and parent pointers after every one.
import random
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key):
self.key, self.left, self.right, self.parent = key, None, None, None
def insert(root, key):
z, y, x = Node(key), None, root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: return z
if key < y.key: y.left = z
else: y.right = z
return root
def right_rotate(root, y):
x = y.left
y.left = x.right
if x.right: x.right.parent = y
x.parent = y.parent
if y.parent is None: root = x
elif y is y.parent.right: y.parent.right = x
else: y.parent.left = x
x.right, y.parent = y, x
return root
def check(root):
out, stack, x = [], [], root
while stack or x:
while x:
for c in (x.left, x.right):
assert c is None or c.parent is x
stack.append(x); x = x.left
x = stack.pop(); out.append(x.key); x = x.right
assert out == sorted(out)
return out
def to_chain(root):
rotations, x = 0, root
while x is not None:
if x.left is not None: # pull the left child up onto the spine
root = right_rotate(root, x)
x = x.parent
rotations += 1
check(root)
else:
x = x.right
return root, rotations
rng = random.Random(6)
for name, keys in [("random 50", rng.sample(range(1000), 50)), ("random 200", rng.sample(range(1000), 200)),
("left path 100", list(range(100, 0, -1)))]:
root = None
for k in keys:
root = insert(root, k)
spine = 0
x = root
while x: spine, x = spine + 1, x.right
root, r = to_chain(root)
assert root.left is None and check(root) == sorted(keys)
print(f"{name:13}: n = {len(keys):3}, right spine at the start {spine} node(s), right rotations {r:3}")random 50 : n = 50, right spine at the start 3 node(s), right rotations 47
random 200 : n = 200, right spine at the start 3 node(s), right rotations 197
left path 100: n = 100, right spine at the start 1 node(s), right rotations 99
The count is exactly minus the number of nodes already on the right spine (root included): every rotation adds one node to the spine, and none ever leaves it. That is at most .
In C++
The C++ version stores nodes in a vector with index 0 as the sentinel nil, the layout used for the red-black tree in the next lessons. Because the sentinel is a real slot, it would be safe to write its parent field unconditionally, but the test on line 3 of LEFT-ROTATE stays: red-black deletion temporarily keeps a meaningful value in the sentinel's parent, and an unguarded rotation could overwrite it. The test applies 100,000 random rotations to a 1000-node tree and checks the inorder sequence at the end.
#include <cstdio>
#include <random>
#include <vector>
struct Tree {
struct Node { int key = 0, left = 0, right = 0, parent = 0; };
std::vector<Node> t{Node{}}; // t[0] is the sentinel nil
int root = 0;
void insert(int key) {
int y = 0, x = root;
while (x != 0) { y = x; x = key < t[x].key ? t[x].left : t[x].right; }
t.push_back({key, 0, 0, y});
int z = static_cast<int>(t.size()) - 1;
if (y == 0) root = z; else if (key < t[y].key) t[y].left = z; else t[y].right = z;
}
void replace_child(int parent, int old, int now) {
if (parent == 0) root = now;
else if (t[parent].left == old) t[parent].left = now;
else t[parent].right = now;
}
void left_rotate(int x) {
int y = t[x].right;
t[x].right = t[y].left;
if (t[y].left != 0) t[t[y].left].parent = x; // keep nil's parent untouched
t[y].parent = t[x].parent;
replace_child(t[x].parent, x, y);
t[y].left = x;
t[x].parent = y;
}
void right_rotate(int y) {
int x = t[y].left;
t[y].left = t[x].right;
if (t[x].right != 0) t[t[x].right].parent = y;
t[x].parent = t[y].parent;
replace_child(t[y].parent, y, x);
t[x].right = y;
t[y].parent = x;
}
void inorder(int x, std::vector<int>& out) const {
if (x == 0) return;
inorder(t[x].left, out); out.push_back(t[x].key); inorder(t[x].right, out);
}
int height(int x) const {
if (x == 0) return -1;
int l = height(t[x].left), r = height(t[x].right);
return 1 + (l > r ? l : r);
}
};
int main() {
Tree tr;
std::mt19937 rng(77);
std::vector<int> keys;
for (int i = 0; i < 1000; ++i) keys.push_back(i * 3);
for (std::size_t i = keys.size() - 1; i > 0; --i) std::swap(keys[i], keys[rng() % (i + 1)]);
for (int k : keys) tr.insert(k);
std::printf("height after random inserts: %d\n", tr.height(tr.root));
long done = 0;
for (int step = 0; step < 100000; ++step) {
int x = 1 + static_cast<int>(rng() % 1000);
if (rng() % 2 == 0) { if (tr.t[x].right != 0) { tr.left_rotate(x); ++done; } }
else if (tr.t[x].left != 0) { tr.right_rotate(x); ++done; }
}
std::vector<int> out;
tr.inorder(tr.root, out);
bool sorted = out.size() == 1000;
for (std::size_t i = 0; sorted && i < out.size(); ++i) sorted = out[i] == static_cast<int>(3 * i);
std::printf("%ld random rotations; inorder still 0, 3, ..., 2997: %s; height now %d\n",
done, sorted ? "yes" : "no", tr.height(tr.root));
}height after random inserts: 19
49744 random rotations; inorder still 0, 3, ..., 2997: yes; height now 73
Random rotations keep the order perfectly, but they wreck the height, from 19 to 73. The point of the red-black fix-ups is to choose which rotations to make, so that the colour properties, and with them the bound, come back.
Test yourself
LEFT-ROTATE with right child : which subtree changes parent?
- 's left subtree
- 's left subtree , which becomes 's right subtree
- 's right subtree
- none
How does a left rotation at change the depths of the subtrees , , ?
- all one level deeper
- one deeper, unchanged, one shallower
- one shallower, one deeper
- nothing changes
What is the time complexity of a rotation?