Kodewick
Start learning →
Balanced trees and B-trees37 / 50

Balanced trees and B-trees

Lesson 37 of 50 · Part 7 · Searching · about 22 minutes

A balanced tree fixes its shape after every insert so the height stays O(log n): an AVL tree rotates whenever the left and right subtree heights differ by more than 1, and a B-tree keeps many keys in each node so the tree stays short.

At the end of the last chapter: 300 values inserted in order into a binary search tree made it 300 tall, and searching fell back to O(n). The binary search tree itself isn't the problem; it's that it doesn't care what shape it grows into. A balanced tree checks its shape after every insert and delete, and when it leans, fixes it, so the height stays O(log n).

AVL trees: left and right differ by at most 1

The AVL tree (named after its two inventors) was the first balanced tree. On top of the binary search tree's rule it adds one more: at every node, the left and right subtrees' heights may differ (the balance factor) only by −1, 0 or 1. After inserting a value, go up from it; the first node whose balance factor has become ±2 is where it's unbalanced, and one rotation there fixes it.

Balance factors are recomputed one by one from the new node upward. Here it is with 10, 20, 30 inserted in that order:

10
20

Under each node, its balance factor (left height − right height): after inserting 30, 10 becomes −2, out of balance
Choose one

Insert 5, 3, 8, 1 in that order into an empty AVL tree (no rotation needed). What is the balance factor of the root, 5?

Exercise 1

Is it balanced?

Decide whether every node's left and right heights differ by at most 1. The trick: check returns the height, and -1 as soon as something is unbalanced, passed all the way up.

It should print
1 0
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val;6    struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10    Node *n = malloc(sizeof(Node));11    n->val = v; n->left = l; n->right = r;12    return n;13}14 15int check(Node *t) {16    // empty: 0; left or right is -1: -1; heights differ by more than 1: -1; otherwise return the height17    return 0;18}19 20int main(void) {21    Node *a = node(1, node(2, node(4, NULL, NULL), NULL), node(3, NULL, NULL));22    Node *b = node(1, node(2, node(4, node(5, NULL, NULL), NULL), NULL), node(3, NULL, NULL));23    printf("%d %d\n", check(a) != -1, check(b) != -1);24    return 0;25}
Output
Press Run or Ctrl+Enter

Four kinds of imbalance, two rotations

After an insertion, walk up from the new node: the first node whose balance factor becomes ±2 is the one to fix. There are only two moves to fix it with: rotating right and rotating left.

There are four kinds, named by "which side of which child of the unbalanced node the new node went into":

ImbalanceThe new node went intoThe fix
LLthe left child's left subtreerotate right once
RRthe right child's right subtreerotate left once
LRthe left child's right subtreerotate the left child left, then this node right
RLthe right child's left subtreerotate the right child right, then this node left

Rotating right: the left child comes up as the root, the old root becomes its right child, and the left child's old right subtree hangs on the old root's left. Rotating left is the mirror image.

3
2
1

LL: insert 3, 2, 1 in that order, and 3's left is 2 tall while its right is 0, unbalanced; one right rotation brings 2 up as the root
3
1
2

LR: insert 3, 1, 2 in that order, and the new node is on the left child's right, one turn isn't enough: rotate 1 left first, making it LL, then rotate 3 right
Choose one

Insert 30, 10, 20 in that order into an empty AVL tree. Which kind of imbalance is it, and what is the root after the fix?

Choose one

When node t is rotated right, where does the old right subtree of its left child l go?

Put in orderDrag, or use the arrows

Put the 6 lines of the left rotation rot_left in order: the right child r comes up and t becomes r's left child.

  1. fix(t);
  2. r->left = t;
  3. Node *r = t->right;
  4. return r;
  5. fix(r);
  6. t->right = r->left;
Should print
2 1 3 
2
Exercise 2

Rotate right

Finish rot_right: the left child l comes up, t becomes l's right child, l's old right subtree hangs on t's left; update t's height first, then l's.

It should print
5 3 1 8 6 9 
height 3
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val, h;6    struct Node *left, *right;7} Node;8 9int H(Node *t) { return t ? t->h : 0; }10int max(int a, int b) { return a > b ? a : b; }11void fix(Node *t) { t->h = max(H(t->left), H(t->right)) + 1; }12 13Node *node(int v, Node *l, Node *r) {14    Node *n = malloc(sizeof(Node));15    n->val = v; n->left = l; n->right = r;16    fix(n);17    return n;18}19 20Node *rot_right(Node *t) {21    // l = t->left; t->left = l->right; l->right = t; fix(t); fix(l); return l22    return t;23}24 25void pre(Node *t) {26    if (!t) return;27    printf("%d ", t->val);28    pre(t->left);29    pre(t->right);30}31 32int main(void) {33    // 8's left, 5(3(1, _), 6), is 2 taller than its right, 9: LL34    Node *t = node(8, node(5, node(3, node(1, NULL, NULL), NULL), node(6, NULL, NULL)), node(9, NULL, NULL));35    t = rot_right(t);36    pre(t);37    printf("\nheight %d\n", t->h);38    return 0;39}
Output
Press Run or Ctrl+Enter

In C: check after every insertion

After the binary search tree's recursive insertion, do two more things: update this node's height h and work out its balance factor; if it is off by more than 1, rotate according to the four cases and hand the new root back up a level.

main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val, h;                       // h: the height of the subtree it's the root of6    struct Node *left, *right;7} Node;8 9int H(Node *t) { return t ? t->h : 0; }10int max(int a, int b) { return a > b ? a : b; }11void fix(Node *t) { t->h = max(H(t->left), H(t->right)) + 1; }12 13Node *rot_right(Node *t) {            // the left child comes up14    Node *l = t->left;15    t->left = l->right;16    l->right = t;17    fix(t);18    fix(l);19    return l;20}21 22Node *rot_left(Node *t) {             // the right child comes up23    Node *r = t->right;24    t->right = r->left;25    r->left = t;26    fix(t);27    fix(r);28    return r;29}30 31Node *insert(Node *t, int v) {32    if (!t) {33        t = malloc(sizeof(Node));34        t->val = v; t->h = 1; t->left = t->right = NULL;35        return t;36    }37    if (v < t->val) t->left = insert(t->left, v);38    else t->right = insert(t->right, v);39    fix(t);40    int bf = H(t->left) - H(t->right);           // the balance factor41    if (bf > 1 && v < t->left->val) return rot_right(t);                       // LL42    if (bf < -1 && v > t->right->val) return rot_left(t);                      // RR43    if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); }          // LR44    if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); }       // RL45    return t;46}47 48int main(void) {49    Node *t = NULL;50    for (int i = 1; i <= 1000; i++)51        t = insert(t, i);             // in order: a plain binary search tree would be 1000 tall52    printf("AVL tree: 1000 values, height %d, root %d\n", t->h, t->val);53    return 0;54}
Output
AVL tree: 1000 values, height 10, root 512

1000 values inserted in order, and the AVL tree is only 10 tall, about log₂ 1000. Each insert rotates at most twice, and search, insert and delete are all O(log n).

Guess the outputA wrong guess is fine

Insert 1 to 7 into an AVL tree in order. What does preorder print?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val, h;6    struct Node *left, *right;7} Node;8 9int H(Node *t) { return t ? t->h : 0; }10int max(int a, int b) { return a > b ? a : b; }11void fix(Node *t) { t->h = max(H(t->left), H(t->right)) + 1; }12 13Node *rot_right(Node *t) { Node *l = t->left; t->left = l->right; l->right = t; fix(t); fix(l); return l; }14Node *rot_left(Node *t) { Node *r = t->right; t->right = r->left; r->left = t; fix(t); fix(r); return r; }15 16Node *insert(Node *t, int v) {17    if (!t) { t = malloc(sizeof(Node)); t->val = v; t->h = 1; t->left = t->right = NULL; return t; }18    if (v < t->val) t->left = insert(t->left, v);19    else t->right = insert(t->right, v);20    fix(t);21    int bf = H(t->left) - H(t->right);22    if (bf > 1 && v < t->left->val) return rot_right(t);23    if (bf < -1 && v > t->right->val) return rot_left(t);24    if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); }25    if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); }26    return t;27}28 29void pre(Node *t) {30    if (!t) return;31    printf("%d ", t->val);32    pre(t->left);33    pre(t->right);34}35 36int main(void) {37    Node *t = NULL;38    for (int i = 1; i <= 7; i++) t = insert(t, i);39    pre(t);40    printf("\n");41    return 0;42}
Fill inTap one to fill a blank; tap a blank to take it back

Which rotation does the LL case (the new node to the left of the left child) call? Fill in the blank so the tree built from 7 down to 1 stays balanced.

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int val, h;6    struct Node *left, *right;7} Node;8 9int H(Node *t) { return t ? t->h : 0; }10int max(int a, int b) { return a > b ? a : b; }11void fix(Node *t) { t->h = max(H(t->left), H(t->right)) + 1; }12 13Node *rot_right(Node *t) { Node *l = t->left; t->left = l->right; l->right = t; fix(t); fix(l); return l; }14Node *rot_left(Node *t) { Node *r = t->right; t->right = r->left; r->left = t; fix(t); fix(r); return r; }15 16Node *insert(Node *t, int v) {17    if (!t) { t = malloc(sizeof(Node)); t->val = v; t->h = 1; t->left = t->right = NULL; return t; }18    if (v < t->val) t->left = insert(t->left, v);19    else t->right = insert(t->right, v);20    fix(t);21    int bf = H(t->left) - H(t->right);22    if (bf > 1 && v < t->left->val) return (t);23    if (bf < -1 && v > t->right->val) return rot_left(t);24    if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); }25    if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); }26    return t;27}28 29void pre(Node *t) {30    if (!t) return;31    printf("%d ", t->val);32    pre(t->left);33    pre(t->right);34}35 36int main(void) {37    Node *t = NULL;38    for (int i = 7; i >= 1; i--) t = insert(t, i);39    pre(t);40    printf("\n");41    return 0;42}

AVL trees aim for strict balance, so they turn quite a lot on inserts and deletes. Red-black trees relax it a little (the longest path at most twice the shortest) and turn less; C++'s std::map, Java's TreeMap and the Linux scheduler use them. Exams usually ask only about AVL rotations; for red-black trees, "a balanced tree too, and the one used more" is enough.

Choose one

What makes a red-black tree better than an AVL tree?

B-trees: many keys in one node

When there's too much data for memory and it lives on disk, things change: one read from disk takes milliseconds, a hundred thousand times slower than memory, and it always reads a whole block (a few KB). What matters most is how many times the disk is read, which is the tree's height.

A B-tree gives each node many keys and many children: one node is exactly one disk block, its keys sorted, and the child between two keys holds the values between those two keys.

20 · 40
5 · 12
25 · 33
50 · 61

Finding 33 in a B-tree of order 3: each node has several keys; find which two keys it falls between, then go down one level

With 1000 keys a node, three levels hold a billion keys (1000 × 1000 × 1000), and any of them is found in 3 disk reads. A B-tree also keeps all its leaves on the same level: when a node is full on insert it splits in two and moves the middle key up into its parent, so it's always balanced.

Choose one

In the B-tree of order 3 at the start of this stage, how many disk reads does it take to find 61?

B+ trees, and which tree to use

A database doesn't just need to "find one", it often needs to "find a range". The B+ tree is the B-tree reworked for that.

A B+ tree is a variant: all the data sits in the leaves, the inner nodes hold only keys for finding the way, and the leaves are linked in a list. A range query ("scores from 60 to 80") then finds the start and reads along the list. MySQL's InnoDB storage engine and most file systems' indexes are B+ trees.

StructureEach nodeSuitsUsed in
AVL tree1 key, 2 childrenmemory, many lookupstextbooks, exams
Red-black tree1 key, 2 childrenmemory, many inserts and deletes tooC++ map, Java TreeMap
B-tree / B+ treemany keys and childrendisk, where a read is a whole blockdatabase indexes, file systems

In exams: AVL questions give an insert sequence and ask, at each step, whether it's unbalanced, which kind, and what the tree looks like after the turn; or "the fewest nodes in an AVL tree of height h" (N(h) = N(h − 1) + N(h − 2) + 1, N(1) = 1, N(2) = 2). B-trees are usually asked only as ideas: in a B-tree of order m, each node has at most m children, and every node but the root at least ⌈m / 2⌉; all leaves are on one level.

Choose one

In a B-tree of order 5, how many children must every node except the root have, at least?

Choose one

You need the records with a score between 60 and 80 out of several million. Which structure fits best?

Summary

Take-away

Balanced trees: turn when it leans, height stays O(log n)

  • AVL: left and right heights differ by at most 1; after an insert, find the first unbalanced node
  • LL rotate right, RR rotate left, LR left then right, RL right then left
  • Red-black trees balance more loosely and turn less; standard libraries use them
  • B-trees / B+ trees: many keys a node, a short tree, few disk reads; database indexes
1Node *rot_right(Node *t) {2    Node *l = t->left;3    t->left = l->right; l->right = t;4    fix(t); fix(l);5    return l;6}