DS Lab · Experiment 16
Red-black tree insertion and search
CTreesJNTUH R22 · CS306PC
Aim
To write a C program that implements a red-black tree with insertion (including recolouring and rotations) and search, displays the tree with the colour of every node, and checks that the red-black rules hold.
Algorithm
- Each node has a key, a colour (red or black), and pointers to its left child, right child and parent. Empty (
NULL) children count as black leaves. - Insert the key as in a binary search tree and colour the new node red.
- While the new node z is not the root and its parent is red, look at z's uncle (the parent's sibling).
- Case 1, the uncle is red: colour the parent and the uncle black and the grandparent red. Move z up to the grandparent and repeat.
- Case 2, the uncle is black and z is an inner child (for example, the right child of a left child): rotate at the parent so that z becomes an outer child, and continue with the old parent as z.
- Case 3, the uncle is black and z is an outer child: colour the parent black and the grandparent red, then rotate at the grandparent in the opposite direction. The fix-up ends here.
- Colour the root black. (When the parent is a right child, the same cases apply with left and right swapped.)
- Search as in a binary search tree. Display the tree with colours, check the rules, and free all nodes.
Program
#include <stdio.h>
#include <stdlib.h>
#define MAX_INPUT 20
enum colour { RED, BLACK };
struct node {
int key;
enum colour colour;
struct node *left, *right, *parent;
};
struct node *root = NULL;
int is_red(struct node *n) {
return n != NULL && n->colour == RED; /* NULL leaves are black */
}
void rotate_left(struct node *x) {
struct node *y = x->right;
x->right = y->left;
if (y->left != NULL) {
y->left->parent = x;
}
y->parent = x->parent;
if (x->parent == NULL) {
root = y;
} else if (x == x->parent->left) {
x->parent->left = y;
} else {
x->parent->right = y;
}
y->left = x;
x->parent = y;
}
void rotate_right(struct node *x) {
struct node *y = x->left;
x->left = y->right;
if (y->right != NULL) {
y->right->parent = x;
}
y->parent = x->parent;
if (x->parent == NULL) {
root = y;
} else if (x == x->parent->right) {
x->parent->right = y;
} else {
x->parent->left = y;
}
y->right = x;
x->parent = y;
}
void fix_insert(struct node *z) {
while (z != root && is_red(z->parent)) {
struct node *parent = z->parent;
struct node *grand = parent->parent; /* exists: a red parent is never the root */
if (parent == grand->left) {
struct node *uncle = grand->right;
if (is_red(uncle)) {
printf(" Case 1 (uncle %d is red): recolour %d and %d black, %d red\n",
uncle->key, parent->key, uncle->key, grand->key);
parent->colour = BLACK;
uncle->colour = BLACK;
grand->colour = RED;
z = grand;
} else {
if (z == parent->right) {
printf(" Case 2 (uncle black, %d is an inner child): left rotation at %d\n",
z->key, parent->key);
z = parent;
rotate_left(z);
parent = z->parent;
}
printf(" Case 3 (uncle black, outer child): right rotation at %d, "
"%d becomes black and %d red\n", grand->key, parent->key, grand->key);
parent->colour = BLACK;
grand->colour = RED;
rotate_right(grand);
}
} else { /* mirror image: parent is a right child */
struct node *uncle = grand->left;
if (is_red(uncle)) {
printf(" Case 1 (uncle %d is red): recolour %d and %d black, %d red\n",
uncle->key, parent->key, uncle->key, grand->key);
parent->colour = BLACK;
uncle->colour = BLACK;
grand->colour = RED;
z = grand;
} else {
if (z == parent->left) {
printf(" Case 2 (uncle black, %d is an inner child): right rotation at %d\n",
z->key, parent->key);
z = parent;
rotate_right(z);
parent = z->parent;
}
printf(" Case 3 (uncle black, outer child): left rotation at %d, "
"%d becomes black and %d red\n", grand->key, parent->key, grand->key);
parent->colour = BLACK;
grand->colour = RED;
rotate_left(grand);
}
}
}
if (root->colour == RED) {
printf(" Root %d coloured black\n", root->key);
root->colour = BLACK;
}
}
void insert(int key) {
struct node *parent = NULL, *curr = root;
while (curr != NULL) { /* ordinary BST insertion */
parent = curr;
if (key == curr->key) {
printf(" %d is already in the tree, skipped\n", key);
return;
}
curr = (key < curr->key) ? curr->left : curr->right;
}
struct node *z = malloc(sizeof(struct node));
if (z == NULL) {
printf("Memory not available\n");
exit(1);
}
z->key = key;
z->colour = RED; /* a new node is always red */
z->left = z->right = NULL;
z->parent = parent;
if (parent == NULL) {
root = z;
} else if (key < parent->key) {
parent->left = z;
} else {
parent->right = z;
}
fix_insert(z);
}
int search(int key) {
struct node *curr = root;
while (curr != NULL) {
if (key == curr->key) {
return 1;
}
curr = (key < curr->key) ? curr->left : curr->right;
}
return 0;
}
/* Returns the number of black nodes on every path from n down to a NULL leaf,
or -1 if a red node has a red child or two paths have different counts */
int black_count(struct node *n) {
if (n == NULL) {
return 0;
}
if (is_red(n) && (is_red(n->left) || is_red(n->right))) {
return -1;
}
int left = black_count(n->left);
int right = black_count(n->right);
if (left == -1 || right == -1 || left != right) {
return -1;
}
return left + (n->colour == BLACK ? 1 : 0);
}
/* Sideways tree: root on the left, right subtree above, left subtree below */
void print_tree(struct node *n, int level) {
if (n == NULL) {
return;
}
print_tree(n->right, level + 1);
for (int i = 0; i < level; i++) {
printf(" ");
}
printf("%d(%c)\n", n->key, n->colour == RED ? 'R' : 'B');
print_tree(n->left, level + 1);
}
void free_tree(struct node *n) {
if (n != NULL) {
free_tree(n->left);
free_tree(n->right);
free(n);
}
}
int main(void) {
int n, key;
printf("Enter number of keys (1-%d): ", MAX_INPUT);
if (scanf("%d", &n) != 1 || n < 1 || n > MAX_INPUT) {
printf("Invalid number of keys\n");
return 1;
}
printf("Enter %d keys: ", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &key) != 1) {
printf("Invalid input\n");
free_tree(root);
return 1;
}
printf("Insert %d\n", key);
insert(key);
}
printf("\nRed-black tree (R = red, B = black), turned sideways:\n");
print_tree(root, 0);
int blacks = black_count(root);
if (root->colour == BLACK && blacks != -1) {
printf("Check: root is black, no red node has a red child,\n");
printf(" every path from the root down has %d black nodes\n", blacks);
} else {
printf("Check: a red-black rule is broken\n");
}
while (1) {
printf("\nEnter key to search (-1 to stop): ");
if (scanf("%d", &key) != 1 || key == -1) {
break;
}
printf("%d is %s\n", key, search(key) ? "found" : "not found");
}
free_tree(root);
return 0;
}Output
Enter number of keys (1-20): 8
Enter 8 keys: 10 20 30 15 25 5 1 27
Insert 10
Root 10 coloured black
Insert 20
Insert 30
Case 3 (uncle black, outer child): left rotation at 10, 20 becomes black and 10 red
Insert 15
Case 1 (uncle 30 is red): recolour 10 and 30 black, 20 red
Root 20 coloured black
Insert 25
Insert 5
Insert 1
Case 1 (uncle 15 is red): recolour 5 and 15 black, 10 red
Insert 27
Case 2 (uncle black, 27 is an inner child): left rotation at 25
Case 3 (uncle black, outer child): right rotation at 30, 27 becomes black and 30 red
Red-black tree (R = red, B = black), turned sideways:
30(R)
27(B)
25(R)
20(B)
15(B)
10(R)
5(B)
1(R)
Check: root is black, no red node has a red child,
every path from the root down has 2 black nodes
Enter key to search (-1 to stop): 27
27 is found
Enter key to search (-1 to stop): 12
12 is not found
Enter key to search (-1 to stop): -1Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
Checking the run by hand: 30 makes the chain 10 → 20 → 30 with two reds in a row and no uncle, so 20 rotates up and becomes the black root (case 3). 15 has a red parent 10 and a red uncle 30, so they are recoloured (case 1) and the root is coloured black again. 1 causes another recolouring. 27 is the right child of 25, which is a left child, so it first rotates at 25 (case 2) and then at 30 (case 3). The final tree is:
20(B)
/ \
10(R) 27(B)
/ \ / \
5(B) 15(B) 25(R) 30(R)
/
1(R)The program covers insertion and search. Deletion from a red-black tree has more cases and is not included. Instead, black_count checks the red-black rules after all insertions.
Common mistakes
Colouring a new node black. That adds one black node to some paths and breaks the equal black count rule; a new node must be red.
Forgetting to update parent pointers in a rotation, especially
y->left->parent = xand the link from the old parent to the new subtree root.Reading
uncle->colourwhen the uncle isNULL. A missing child counts as black, so use a helper likeis_redthat handlesNULL.Forgetting to colour the root black at the end of the fix-up, since case 1 can make the root red.
Viva questions
Try to answer each one aloud before you open it.
What are the properties of a red-black tree?
Every node is red or black. The root is black. All NULL (NIL) leaves are black. A red node cannot have a red child. Every path from a node down to its NULL leaves has the same number of black nodes.
Why is a newly inserted node coloured red?
A red node does not change the number of black nodes on any path, so the black count rule stays true. Only the 'no two reds in a row' rule may break, and the fix-up repairs that.
What is the height of a red-black tree with n nodes?
At most 2 log₂(n + 1). So search, insert and delete take O(log n) time.
How is a red-black tree different from an AVL tree?
An AVL tree is more strictly balanced, so searches are slightly faster. A red-black tree allows more imbalance but needs fewer rotations on insert and delete, so it is often preferred when there are many updates.
Where are red-black trees used?
In library containers such as C++
std::mapandstd::set(in common implementations), Java'sTreeMap, and the Linux kernel's scheduler.