Example 1 — Fix a right-heavy chain with one rotation
Keys 10, 20, 30 inserted in order form a chain.
#include <stdio.h>
struct T { int key; struct T *left, *right; };
static int height(const struct T *t) {
if (!t) return -1;
int a = height(t->left), b = height(t->right);
return 1 + (a > b ? a : b);
}
static int balance(const struct T *t) {
return height(t->left) - height(t->right);
}
static struct T *rotate_left(struct T *x) {
struct T *y = x->right;
x->right = y->left;
y->left = x;
return y;
}
int main(void) {
struct T n30 = {30, NULL, NULL};
struct T n20 = {20, NULL, &n30};
struct T n10 = {10, NULL, &n20};
struct T *root = &n10;
printf("before: root=%d height=%d balance=%d\n",
root->key, height(root), balance(root));
root = rotate_left(root);
printf("after left rotation: root=%d height=%d balance=%d\n",
root->key, height(root), balance(root));
return 0;
} How It Works
- The chain 10, 20, 30 has height 2 and balance -2 (too right-heavy).
- Rotating left makes 20 the root with 10 and 30 as children.
- Height drops to 1 and the tree stays a valid BST.
