Balance factor
int balanceFactor(Node n) {
return height(n.left) - height(n.right);
}Advertisement
Left rotation
Node rotateLeft(Node a) {
Node b = a.right;
a.right = b.left;
b.left = a;
updateHeight(a); updateHeight(b);
return b;
}Advertisement
Four cases
- LL: right rotation.
- RR: left rotation.
- LR: left then right (double).
- RL: right then left (double).
Complexity
Insert + delete + search: O(log N). Rotation cost: O(1) per rotation, O(log N) rotations per insert.
Balance factor
int balanceFactor(Node n) {
return height(n.left) - height(n.right);
}Left rotation
Node rotateLeft(Node a) {
Node b = a.right;
a.right = b.left;
b.left = a;
updateHeight(a); updateHeight(b);
return b;
}Four cases
- LL: right rotation.
- RR: left rotation.
- LR: left then right (double).
- RL: right then left (double).
Complexity
Insert + delete + search: O(log N). Rotation cost: O(1) per rotation, O(log N) rotations per insert.