DS Lab · Experiment 14
B+ tree insertion and search
CTreesJNTUH R22 · CS306PC
Aim
To write a C program that implements a B+ tree of order 3 with insertion (including leaf and internal node splits) and search, and displays the tree level by level along with the linked list of leaves.
Algorithm
- In a B+ tree of order m, every node holds at most m − 1 keys. All keys are stored in the leaves; internal nodes hold only copies of keys that guide the search. The leaves are linked left to right. Here m = 3.
- Insert key: go down from the root. In an internal node, move to the child on the right of every separator key that is less than or equal to the key. Insert the key in sorted order in the leaf that is reached.
- If a leaf now has m keys, split it: the left leaf keeps the first ⌈m/2⌉ keys and a new right leaf takes the rest. Link the new leaf into the leaf chain, and copy the first key of the new leaf up into the parent (it also stays in the leaf).
- If an internal node now has m keys, split it: the middle key moves up to the parent (it is not kept in either half), the keys on its left stay, and the keys on its right go into a new internal node with their children.
- Repeat the split on the way up as needed. If the root splits, create a new root with the key that moved up.
- Search key: go down from the root in the same way as insertion until a leaf is reached, and look for the key in that leaf.
- Display the tree level by level, then print the leaf chain from left to right. Free all nodes.
Program
#include <stdio.h>
#include <stdlib.h>
#define ORDER 3 /* maximum number of children */
#define MAX_KEYS (ORDER - 1) /* maximum number of keys in a node */
#define MAX_INPUT 20
struct node {
int nkeys;
int keys[ORDER]; /* one extra slot holds a key just before a split */
struct node *child[ORDER + 1];
struct node *next; /* leaves only: the next leaf to the right */
int leaf;
};
struct node *new_node(int leaf) {
struct node *n = malloc(sizeof(struct node));
if (n == NULL) {
printf("Memory not available\n");
exit(1);
}
n->nkeys = 0;
n->leaf = leaf;
n->next = NULL;
for (int i = 0; i <= ORDER; i++) {
n->child[i] = NULL;
}
return n;
}
void print_node(struct node *n) {
printf("[");
for (int i = 0; i < n->nkeys; i++) {
printf(i == 0 ? "%d" : " %d", n->keys[i]);
}
printf("]");
}
/* Index of the child to follow: keys equal to a separator go right */
int child_index(struct node *n, int key) {
int i = 0;
while (i < n->nkeys && key >= n->keys[i]) {
i++;
}
return i;
}
/* Leaf split: the first key of the new right leaf is COPIED up */
void split_leaf(struct node *n, int *up_key, struct node **right) {
int keep = (n->nkeys + 1) / 2;
struct node *r = new_node(1);
for (int j = keep; j < n->nkeys; j++) {
r->keys[r->nkeys++] = n->keys[j];
}
n->nkeys = keep;
r->next = n->next; /* link the new leaf into the chain */
n->next = r;
*up_key = r->keys[0];
*right = r;
printf(" Leaf split into ");
print_node(n);
printf(" and ");
print_node(r);
printf(", %d copied up\n", *up_key);
}
/* Internal split: the middle key MOVES up */
void split_internal(struct node *n, int *up_key, struct node **right) {
int mid = n->nkeys / 2;
struct node *r = new_node(0);
printf(" Internal node ");
print_node(n);
printf(" split, %d moves up\n", n->keys[mid]);
*up_key = n->keys[mid];
for (int j = mid + 1; j < n->nkeys; j++) {
r->keys[r->nkeys++] = n->keys[j];
}
for (int j = mid + 1; j <= n->nkeys; j++) {
r->child[j - mid - 1] = n->child[j];
}
n->nkeys = mid;
*right = r;
}
/* Returns 1 if node n was split (caller takes *up_key and *right) */
int insert_rec(struct node *n, int key, int *up_key, struct node **right) {
int i;
if (n->leaf) {
i = n->nkeys - 1;
while (i >= 0 && n->keys[i] > key) {
n->keys[i + 1] = n->keys[i];
i--;
}
n->keys[i + 1] = key;
n->nkeys++;
if (n->nkeys <= MAX_KEYS) {
return 0;
}
split_leaf(n, up_key, right);
return 1;
}
int pos = child_index(n, key);
int mid_key = 0;
struct node *new_child = NULL;
if (!insert_rec(n->child[pos], key, &mid_key, &new_child)) {
return 0;
}
for (i = n->nkeys; i > pos; i--) { /* make room at pos */
n->keys[i] = n->keys[i - 1];
n->child[i + 1] = n->child[i];
}
n->keys[pos] = mid_key;
n->child[pos + 1] = new_child;
n->nkeys++;
if (n->nkeys <= MAX_KEYS) {
return 0;
}
split_internal(n, up_key, right);
return 1;
}
int search(struct node *root, int key) {
struct node *n = root;
if (n == NULL) {
return 0;
}
while (!n->leaf) { /* every search ends at a leaf */
n = n->child[child_index(n, key)];
}
for (int i = 0; i < n->nkeys; i++) {
if (n->keys[i] == key) {
return 1;
}
}
return 0;
}
struct node *insert(struct node *root, int key) {
printf("Insert %d\n", key);
if (root == NULL) {
root = new_node(1);
root->keys[0] = key;
root->nkeys = 1;
return root;
}
if (search(root, key)) {
printf(" %d is already in the tree, skipped\n", key);
return root;
}
int up_key = 0;
struct node *right = NULL;
if (insert_rec(root, key, &up_key, &right)) {
struct node *new_root = new_node(0);
new_root->keys[0] = up_key;
new_root->nkeys = 1;
new_root->child[0] = root;
new_root->child[1] = right;
printf(" New root [%d] created\n", up_key);
return new_root;
}
return root;
}
void display(struct node *root) {
struct node *queue[100];
int level[100];
int front = 0, rear = 0, current = -1;
queue[rear] = root;
level[rear++] = 0;
while (front < rear) {
struct node *n = queue[front];
int lv = level[front++];
if (lv != current) {
printf(current == -1 ? "Level %d: " : "\nLevel %d: ", lv);
current = lv;
}
print_node(n);
printf(" ");
if (!n->leaf) {
for (int i = 0; i <= n->nkeys; i++) {
queue[rear] = n->child[i];
level[rear++] = lv + 1;
}
}
}
printf("\n");
struct node *leaf = root; /* leftmost leaf */
while (!leaf->leaf) {
leaf = leaf->child[0];
}
printf("Leaf chain: ");
for (; leaf != NULL; leaf = leaf->next) {
print_node(leaf);
printf(leaf->next != NULL ? " -> " : " -> NULL\n");
}
}
void free_tree(struct node *n) {
if (n == NULL) {
return;
}
if (!n->leaf) {
for (int i = 0; i <= n->nkeys; i++) {
free_tree(n->child[i]);
}
}
free(n);
}
int main(void) {
struct node *root = NULL;
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;
}
root = insert(root, key);
}
printf("\nB+ tree of order %d:\n", ORDER);
display(root);
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(root, key) ? "found" : "not found");
}
free_tree(root);
return 0;
}Output
Enter number of keys (1-20): 8
Enter 8 keys: 10 20 5 6 12 30 7 17
Insert 10
Insert 20
Insert 5
Leaf split into [5 10] and [20], 20 copied up
New root [20] created
Insert 6
Leaf split into [5 6] and [10], 10 copied up
Insert 12
Insert 30
Insert 7
Leaf split into [5 6] and [7], 7 copied up
Internal node [7 10 20] split, 10 moves up
New root [10] created
Insert 17
Leaf split into [10 12] and [17], 17 copied up
B+ tree of order 3:
Level 0: [10]
Level 1: [7] [17 20]
Level 2: [5 6] [7] [10 12] [17] [20 30]
Leaf chain: [5 6] -> [7] -> [10 12] -> [17] -> [20 30] -> NULL
Enter key to search (-1 to stop): 10
10 is found
Enter key to search (-1 to stop): 15
15 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: inserting 5 makes the leaf [5 10 20], which splits into [5 10] and [20], and 20 is copied up as the root. 6 splits [5 6 10] and copies 10 up. Inserting 7 splits [5 6 7]; 7 is copied up and makes the root [7 10 20] too full, so the root splits and 10 moves up. Finally 17 splits [10 12 17]. The final tree is:
[10]
/ \
[7] [17 20]
/ \ / | \
[5 6] [7] [10 12] [17] [20 30]Notice that 7, 10, 17 and 20 appear both in an internal node and in a leaf: in a B+ tree the internal keys are only signposts, and every key is stored in a leaf. The leaf chain gives all keys in sorted order without going back up the tree.
The program covers insertion and search. Deletion (borrowing from or merging with a sibling leaf) is not included. Textbooks differ on whether the left or the right half gets the extra key in a leaf split; this program keeps ⌈m/2⌉ keys in the left leaf.
Common mistakes
Moving the middle key up when a leaf splits, as in a B-tree. In a B+ tree the key is copied up and also stays in the new leaf, because every key must be in a leaf.
Copying the middle key up when an internal node splits. Internal splits work like a B-tree: the key moves up and is not kept below.
Forgetting to link the new leaf into the leaf chain (
r->next = n->next; n->next = r;), so the sorted leaf list skips keys.Stopping a search at an internal node because the key matches a separator. The search must always continue to a leaf, where the real key is stored.
Viva questions
Try to answer each one aloud before you open it.
How is a B+ tree different from a B-tree?
In a B+ tree all keys (and their data) are stored in the leaves, internal nodes hold only copies of keys for guiding the search, and the leaves are linked together. In a B-tree, keys and data can be in any node and each key appears only once.
Why are the leaves of a B+ tree linked?
So that all keys can be read in sorted order, and range queries such as 'all keys from 10 to 20' can be answered by finding the first key and then walking along the leaves.
Why do databases prefer B+ trees for indexes?
Internal nodes hold only keys, so more keys fit in one disk block and the tree is shorter. Range scans and full sorted scans are fast because of the linked leaves.
What is the time complexity of a search in a B+ tree?
O(log n). Every search goes from the root to a leaf, and the height is O(log n).
What happens to the key that goes up when a leaf splits?
It is copied: the first key of the new right leaf is placed in the parent as a separator and also stays in the leaf.