---
title: "Binary Search Trees and Balanced Trees"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 17
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/17-binary-search-trees-and-balanced-trees
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 17 — Binary Search Trees and Balanced Trees

The town library keeps its catalogue in a search tree, so that a title is found by a few comparisons and the titles can be listed in alphabetical order. One year the librarian rebuilds the tree by inserting the titles in alphabetical order, from a printed list. The new tree answers correctly, but every search now takes forty comparisons on average instead of a handful: the tree has become a [linked list](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#def-b1-linked-structures-list). This chapter builds search trees, measures how their shape depends on the order of insertion, and makes two kinds of trees that keep their height logarithmic whatever the order: [AVL trees](#def-b1-balanced-trees-avl) and [red-black trees](#def-b1-balanced-trees-rb).

**You already know.**

A [binary tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) is empty or a root with a left and a right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree); its height is the number of edges on a longest path from the root down, $-1$ for the empty tree ([Definition 11.4](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-height)). Properties of trees are proved by [structural induction](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-structural) ([Definition 11.5](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-structural)). A [dictionary](https://one-course.com/books/computer-science/3/en/chapter/16-hash-tables#def-b1-hash-tables-dictionary) associates values with keys ([Definition 16.1](https://one-course.com/books/computer-science/3/en/chapter/16-hash-tables#def-b1-hash-tables-dictionary)).

## 17.1 Binary search trees

**Definition 17.1 (Binary search tree).**

A *binary search tree* is a [binary tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) whose nodes hold keys from an ordered set, with the *search-tree property*: at every node, the keys of the left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) are smaller than the node’s key, and the keys of the right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) are larger.

A search compares the key with the root’s and goes left or right; it follows one path, so it costs $O(h)$ for a tree of height $h$. Insertion searches, and puts the new node where the search fell off the tree.

```c
const char *bst_floor(const node *t, const char *key) {
    const char *best = NULL;
    while (t != NULL) {
        int c = strcmp(key, t->key);
        if (c == 0) return t->key;
        if (c < 0) t = t->left;
        else best = t->key, t = t->right;  // a candidate; a larger one may be on the right
    }
    return best;
}
```

***Listing 17.1.** The floor: the largest key at most `key` code/bachelor-1/17-balanced-trees/listings/bst.c*

**Definition 17.2 (Traversals).**

The *in-order traversal* of a [binary tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) visits the left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), then the root, then the right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree); the *preorder* visits the root first, the *postorder* last.

**Proposition 17.3 (In-order is sorted).**

The [in-order traversal](#def-b1-balanced-trees-traversal) of a [binary search tree](#def-b1-balanced-trees-bst) visits its keys in increasing order.

**Proof.** By [structural induction](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-structural). The empty tree visits nothing. For a root $r$ with [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) $L$ and $R$, the traversal visits the keys of $L$ in increasing order (hypothesis), all smaller than $r$ ([search-tree property](#def-b1-balanced-trees-bst)), then $r$, then the keys of $R$ in increasing order, all larger than $r$. ∎

**Definition 17.4 (Ordered dictionary, successor).**

An *ordered dictionary* is a [dictionary](https://one-course.com/books/computer-science/3/en/chapter/16-hash-tables#def-b1-hash-tables-dictionary) whose keys are ordered, with the further operations minimum, maximum, floor (the largest key at most $k$), ceiling, *successor* (the smallest key larger than $k$), and the listing of the keys between two bounds.

A [hash table](https://one-course.com/books/computer-science/3/en/chapter/16-hash-tables#def-b1-hash-tables-hash-table) cannot answer these questions without examining every key; a search tree answers each by one path. The floor goes right whenever the node’s key is small enough, remembering it as a candidate, since a larger candidate can only be on its right.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o bst_demo bst_demo.c bst.c -lm && ./bst_demo
        Zoe
    Tom
        Pia
Mia
            Kai
        Ivy
            Gus
    Eli
        Bea
in order: Bea Eli Gus Ivy Kai Mia Pia Tom Zoe
height 3, size 9
floor("Jo") = Ivy, next("Jo") = Kai, next("Zoe") = (none)
after deleting Eli:
        Zoe
    Tom
        Pia
Mia
            Kai
        Ivy
    Gus
        Bea
```

***Output 17.1.** Nine names, drawn sideways (root on the left, right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) above); the deletion of a node with two children.*

Deletion has three cases. A [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) is removed. A node with one child is replaced by that child. A node with two children takes the key of its [successor](#def-b1-balanced-trees-ordered), the minimum of its right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), which has no left child, and that [successor](#def-b1-balanced-trees-ordered) is deleted from the right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) by one of the first two cases.

```c
node *bst_delete(node *t, const char *key) {
    if (t == NULL) return NULL;
    int c = strcmp(key, t->key);
    if (c < 0) t->left = bst_delete(t->left, key);
    else if (c > 0) t->right = bst_delete(t->right, key);
    else if (t->left == NULL || t->right == NULL) {  // zero or one child: splice it out
        node *child = t->left != NULL ? t->left : t->right;
        free(t);
        return child;
    } else {  // two children: take the successor's key, then delete the successor
        const node *s = bst_min(t->right);
        t->key = s->key, t->value = s->value;
        t->right = bst_delete(t->right, s->key);
    }
    return t;
}
```

***Listing 17.2.** Deletion: the two-child case moves the [successor](#def-b1-balanced-trees-ordered) up code/bachelor-1/17-balanced-trees/listings/bst.c*

![Left: the tree of and the path of the search for the floor of Jo (shaded): Mia, Eli, Ivy and Kai; the answer is Ivy, the last node where the search went right. Right: after deleting Eli, its successor Gus has taken its place.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-balanced-trees/fig-3f1cede50128.svg)

*Left: the tree of [Output 17.1](#out-b1-balanced-trees-demo) and the path of the search for the floor of `Jo` (shaded): Mia, Eli, Ivy and Kai; the answer is Ivy, the last node where the search went right. Right: after deleting Eli, its [successor](#def-b1-balanced-trees-ordered) Gus has taken its place.*

## 17.2 Height bounds

Every operation of the previous section costs $\Theta(h)$ in the worst case. The height depends on the order of the insertions, not only on the keys.

**Proposition 17.5 (Height of a binary tree).**

A [binary tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) with $n \geq 1$ nodes has height $h$ with $\lfloor \log_2 n \rfloor \leq h \leq n - 1$.

**Proof.** A longest path holds $h + 1$ nodes, all distinct, so $n \geq h + 1$. Depth $d$ holds at most $2^d$ nodes, so $n \leq 1 +
2 + \dots + 2^h = 2^{h+1} - 1 < 2^{h+1}$, and $\log_2 n < h + 1$, that is $\lfloor \log_2 n \rfloor \leq h$. ∎

**Definition 17.6 (Degenerate tree).**

A tree is *degenerate* when every node has at most one child: its height is $n - 1$, and it is a [linked list](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#def-b1-linked-structures-list).

Inserting keys in increasing order builds a [degenerate tree](#def-b1-balanced-trees-degenerate): each new key is larger than all the others and goes to the right of the rightmost node. The town’s 80 titles show the three regimes.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o heights heights.c bst.c avl.c llrb.c -lm && ./heights
  n catalogue sorted shuffled   AVL  LLRB floor(lg n)
  5         3      4     2.78     2     2          2
 10         5      9     4.68     3     3          3
 15         6     14     5.82     4     4          3
 20         7     19     6.68     4     5          4
 25         7     24     7.44     5     5          4
 30         8     29     8.06     5     5          4
 35         8     34     8.55     5     6          5
 40         9     39     8.99     5     5          5
 45         9     44     9.33     5     5          5
 50         9     49     9.84     6     6          5
 55        10     54    10.12     6     6          5
 60        10     59    10.40     6     7          5
 65        11     64    10.69     6     6          6
 70        11     69    11.03     6     7          6
 75        11     74    11.23     7     7          6
 80        11     79    11.39     7     7          6
AVL, 80 titles in catalogue order: 22 single and 11 double rotations, height 7
AVL, 80 titles in alphabetical order: 73 single and 0 double rotations, height 6
LLRB, catalogue order: height 7, black height 5
```

***Output 17.2.** Heights of trees built from the first $n$ titles. The last three lines are used by the problem.*

![Heights from . The alphabetical order climbs as n - 1 and leaves the chart at n = 27; random orders grow slowly; the AVL tree stays within one or two of the lower bound.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-balanced-trees/fig-31afee60ea2f.svg)

*Heights from [Output 17.2](#out-b1-balanced-trees-heights). The alphabetical order climbs as $n - 1$ and leaves the chart at $n = 27$; random orders grow slowly; the [AVL tree](#def-b1-balanced-trees-avl) stays within one or two of the lower bound.*

A random order of insertion gives, on average, a height of order $\log n$; the average depth of a node is about $2 \ln n
\approx 1.39 \log_2 n$, a result of the second year. Input does not come in random order: sorted files, increasing identifiers and timestamps are common. Balanced trees guarantee $O(\log n)$ for every order, by repairing the tree after each insertion with [rotations](#def-b1-balanced-trees-rotation).

## 17.3 Rotations

**Definition 17.7 (Rotation).**

A *right rotation* at a node $y$ with left child $x$ makes $x$ the root of the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), $y$ its right child, and the former right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of $x$ the left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of $y$. A *left rotation* is the inverse operation.

![A rotation changes three links. The in-order sequence is A, x, B, y, C on both sides; the subtree B (shaded) changes parent; A moves up a level and C down a level.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-balanced-trees/fig-7b8e0b018b19.svg)

*A [rotation](#def-b1-balanced-trees-rotation) changes three links. The in-order sequence is $A, x, B, y, C$ on both sides; the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) $B$ (shaded) changes parent; $A$ moves up a level and $C$ down a level.*

**Proposition 17.8 (Rotations preserve the order).**

A [rotation](#def-b1-balanced-trees-rotation) of a [binary search tree](#def-b1-balanced-trees-bst) yields a [binary search tree](#def-b1-balanced-trees-bst) with the same keys and the same in-order sequence.

**Proof.** Before a [right rotation](#def-b1-balanced-trees-rotation), the in-order sequence of the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) is $A, x, B, y, C$, where $A$, $B$ and $C$ stand for the sequences of the three [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree): $x$ is the left child of $y$, $A$ and $B$ its [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree). After it, $x$ is the root with left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) $A$ and right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) $y$, whose [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) are $B$ and $C$: the sequence is again $A, x, B, y, C$. The rest of the tree, outside the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), is unchanged, and the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree)’s set of keys too, so the property holds everywhere. ∎

```c
static avl *rotate_right(avl *y) {  // the left child x becomes the root of the subtree
    avl *x = y->left;
    y->left = x->right;  // the middle subtree changes parent
    x->right = y;
    update(y);
    update(x);
    return x;
}
```

***Listing 17.3.** A [right rotation](#def-b1-balanced-trees-rotation), with the stored heights updated code/bachelor-1/17-balanced-trees/listings/avl.c*

## 17.4 AVL trees

**Definition 17.9 (Balance factor, AVL tree).**

The *balance factor* of a node is the height of its right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) minus the height of its left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree). An *AVL tree* is a [binary search tree](#def-b1-balanced-trees-bst) in which every node has balance factor $-1$, 0 or 1.

[AVL trees](#def-b1-balanced-trees-avl) take their name from G. M. Adelson-Velsky and E. M. Landis, who published them in 1962. Each node stores its height. After an insertion, the heights change only on the path from the new node up to the root, and a node on it may reach [balance factor](#def-b1-balanced-trees-avl) $\pm 2$. Four cases repair it, named after the path from the unbalanced node to the new key: a single [rotation](#def-b1-balanced-trees-rotation) when the path goes twice the same way (LL or RR), a double [rotation](#def-b1-balanced-trees-rotation) when it turns (LR or RL), which first rotates the child the other way.

```c
static avl *rebalance(avl *t) {
    update(t);
    if (balance(t) == -2) {  // left-heavy
        if (balance(t->left) > 0) t->left = rotate_left(t->left), avl_double++;  // case LR
        else avl_single++;                                                       // case LL
        return rotate_right(t);
    }
    if (balance(t) == 2) {  // right-heavy: the mirror image
        if (balance(t->right) < 0) t->right = rotate_right(t->right), avl_double++;  // RL
        else avl_single++;                                                          // RR
        return rotate_left(t);
    }
    return t;
}
```

***Listing 17.4.** Rebalancing on the way back up code/bachelor-1/17-balanced-trees/listings/avl.c*

![Two of the four rebalancing cases, on three keys; the new key is shaded. The node 3 has balance factor -2. When the new key lies left of its left child (LL), one right rotation at 3 restores the balance. When it lies to the right of its left child (LR), a left rotation at 1 turns the case into LL. RR and RL are the mirror images.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-balanced-trees/fig-7e47e529fc87.svg)

*Two of the four rebalancing cases, on three keys; the new key is shaded. The node 3 has [balance factor](#def-b1-balanced-trees-avl) $-2$. When the new key lies left of its left child (LL), one [right rotation](#def-b1-balanced-trees-rotation) at 3 restores the balance. When it lies to the right of its left child (LR), a left [rotation](#def-b1-balanced-trees-rotation) at 1 turns the case into LL. RR and RL are the mirror images.*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o avl_demo avl_demo.c avl.c -lm && ./avl_demo
insert C : single rotation
insert E : single rotation
insert F : single rotation
insert G : single rotation
insert I : single rotation
insert J : single rotation
insert Fa: double rotation
insert Fb: double rotation
12 keys, height 3, valid AVL tree: yes
            J (+0)
        I (+1)
    H (+0)
            G (+0)
        Fb (+0)
            Fa (+0)
F (+0)
        E (+0)
    D (-1)
            C (+0)
        B (+0)
            A (+0)
```

***Output 17.3.** Increasing keys, then two keys that need double [rotations](#def-b1-balanced-trees-rotation); [balance factors](#def-b1-balanced-trees-avl) in parentheses.*

Ten increasing keys, which built a [degenerate tree](#def-b1-balanced-trees-degenerate) of height 9 in a plain search tree, give an [AVL tree](#def-b1-balanced-trees-avl) of height 3. The cost of an insertion is the descent, $O(h)$, plus constant work at each node of the way back up: at most one [rotation](#def-b1-balanced-trees-rotation) event happens per insertion ([Exercise 17.11](#exo-b1-balanced-trees-11)). The height is guaranteed by counting the smallest trees.

**Theorem 17.10 (Height of an AVL tree).**

An [AVL tree](#def-b1-balanced-trees-avl) with $n$ nodes has height $h \leq \log_\varphi (n + 1) - 1 < 1.45 \log_2 (n + 2)$, where $\varphi = (1 +
\sqrt 5)/2$.

**Proof.** Let $N(h)$ be the smallest number of nodes of an [AVL tree](#def-b1-balanced-trees-avl) of height $h$: $N(0) = 1$, $N(1) = 2$. A smallest tree of height $h \geq 2$ has one [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of height $h - 1$ and, since the [balance factor](#def-b1-balanced-trees-avl) is at most 1 in absolute value and the tree is smallest, the other of height $h - 2$, both smallest themselves: $N(h) = N(h - 1) + N(h - 2) + 1$. With the Fibonacci numbers $F_0 = 0$, $F_1 = 1$, $F_{k+2} = F_{k+1} + F_k$, induction gives $N(h) = F_{h+3} - 1$, and $F_k \geq
\varphi^{k-2}$ for $k \geq 1$ (problem, Part IV). So $n \geq N(h) \geq \varphi^{h+1} - 1$, and $h + 1 \leq \log_\varphi
(n + 1)$. Finally $1/\log_2 \varphi \approx 1.4404$. ∎

```
$ python minimal_avl.py
 h   N(h)  F(h+3)-1  1.44 lg(N+2)
 0      1         1          2.28
 1      2         2          2.88
 2      4         4          3.72
 3      7         7          4.57
 4     12        12          5.48
 5     20        20          6.42
 6     33        33          7.39
 7     54        54          8.37
 8     88        88          9.35
 9    143       143         10.34
10    232       232         11.34
15   2583      2583         16.33
20  28656     28656         21.33
largest height of an AVL tree with 80 nodes: 7
```

***Output 17.4.** Minimal [AVL trees](#def-b1-balanced-trees-avl), built as trees and counted.*

## 17.5 Red-black trees

**Definition 17.11 (Red-black tree, black height).**

A *red-black tree* is a [binary search tree](#def-b1-balanced-trees-bst) whose nodes are coloured red or black, such that the root is black, a red node has no red child, and every path from a node down to an empty [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) contains the same number of black nodes, the *black height* of the node. A *left-leaning red-black tree* is a red-black tree in which every red node is a left child.

[Red-black trees](#def-b1-balanced-trees-rb) were introduced by L. Guibas and R. Sedgewick in 1978; the left-leaning variant is Sedgewick’s. A red node and its parent can be read as one node with two keys: a [left-leaning red-black tree](#def-b1-balanced-trees-rb) is then a *2-3 tree*, whose nodes hold one or two keys and whose empty [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) are all at the same depth. Three local repairs, on the way back up after inserting a red node, keep the colour rules: a red right link is rotated to the left, two red links in a row are rotated right, and a node with two red children passes its red up by a colour flip.

```c
static rb *put(rb *h, const char *key, int value) {
    if (h == NULL) {
        rb *n = malloc(sizeof *n);
        if (n == NULL) exit(1);
        *n = (rb){key, value, true, NULL, NULL};  // a new key joins its parent's node
        return n;
    }
    int c = strcmp(key, h->key);
    if (c < 0) h->left = put(h->left, key, value);
    else if (c > 0) h->right = put(h->right, key, value);
    else h->value = value;
    if (is_red(h->right) && !is_red(h->left)) h = rotate_left(h);
    if (is_red(h->left) && is_red(h->left->left)) h = rotate_right(h);
    if (is_red(h->left) && is_red(h->right)) flip(h);
    return h;
}
```

***Listing 17.5.** Insertion in a [left-leaning red-black tree](#def-b1-balanced-trees-rb) code/bachelor-1/17-balanced-trees/listings/llrb.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o llrb_demo llrb_demo.c llrb.c -lm && ./llrb_demo
10 keys, height 3, black height 3, valid: yes
        J
            *I
    H
            G
        *F
            E
D
        C
    B
        A
```

***Output 17.5.** The same ten increasing keys; red nodes are starred.*

![Left: the left-leaning red-black tree of , red nodes shaded; every path from the root to an empty subtree meets three black nodes. Right: the same tree read as a 2-3 tree, each red node merged with its parent: all leaves at depth 2.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-balanced-trees/fig-a703430a863b.svg)

*Left: the [left-leaning red-black tree](#def-b1-balanced-trees-rb) of [Output 17.5](#out-b1-balanced-trees-llrb-demo), red nodes shaded; every path from the root to an empty [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) meets three black nodes. Right: the same tree read as a 2-3 tree, each red node merged with its parent: all leaves at depth 2.*

**Theorem 17.12 (Height of a red-black tree).**

A [red-black tree](#def-b1-balanced-trees-rb) with $n$ nodes has height $h$ with $h + 1 \leq 2 \log_2 (n + 1)$.

The proof ([Exercise 17.10](#exo-b1-balanced-trees-10)) counts at least $2^b - 1$ nodes below a node of [black height](#def-b1-balanced-trees-rb) $b$, and at least one black node out of two on any path. The bound is weaker than the [AVL tree](#def-b1-balanced-trees-avl)’s, $2$ against $1.44$, but the repairs are simpler, and deletion needs at most a constant number of [rotations](#def-b1-balanced-trees-rotation) in the classic version. The standard libraries of C++ and Java implement their ordered maps as [red-black trees](#def-b1-balanced-trees-rb); the left-leaning variant shown here is shorter to write, and its deletion, not written here, is shorter too.

## 17.6 Serialising a tree

**Definition 17.13 (Serialisation).**

The *serialisation* of a data structure is a sequence of bytes, or of characters, from which the structure can be rebuilt, in another run or on another machine; [pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) are not part of it, since they are only meaningful in one address space.

A [preorder](#def-b1-balanced-trees-traversal) traversal that writes a marker for each empty [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) describes the shape completely: reading it back, the first item is the root, then comes the left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), written in the same way, then the right one.

```c
static void write_tree(const node *t, FILE *f) {
    if (t == NULL) {
        fputs("# ", f);
        return;
    }
    fprintf(f, "%s %d ", t->key, t->value);
    write_tree(t->left, f);
    write_tree(t->right, f);
}

static char store[100][32];  // the keys read back live here
static int stored;

static node *read_tree(FILE *f) {
    char word[32];
    if (fscanf(f, "%31s", word) != 1 || strcmp(word, "#") == 0) return NULL;
    node *t = malloc(sizeof *t);
    if (t == NULL || stored == 100 || fscanf(f, "%d", &t->value) != 1) exit(1);
    t->key = strcpy(store[stored++], word);
    t->left = read_tree(f);  // the same order as the writing
    t->right = read_tree(f);
    return t;
}
```

***Listing 17.6.** Writing and reading a tree in [preorder](#def-b1-balanced-trees-traversal) with markers code/bachelor-1/17-balanced-trees/listings/serialise.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o serialise serialise.c bst.c -lm && ./serialise
file: Mia 0 Eli 1 Bea 3 # # Ivy 4 # # Tom 2 Pia 5 # # Zoe 6 # #
read back: height 2, size 7
        Zoe
    Tom
        Pia
Mia
        Ivy
    Eli
        Bea
```

***Output 17.6.** A tree written to a file and read back.*

**In practice.**

For a search tree, the sorted list of keys is enough to rebuild a balanced tree in linear time ([Exercise 17.12](#exo-b1-balanced-trees-12)), and it is the better file format: it does not depend on the shape, which is an accident of the insertion order. The [preorder](#def-b1-balanced-trees-traversal) with markers is needed when the shape itself is the information, as in an expression tree or a decision tree.

## 17.7 Exercises

**Exercise 17.1 ★.**

The keys 50, 30, 70, 20, 40, 60, 80, 35 are inserted in this order into an empty search tree. Give the in-order, the [preorder](#def-b1-balanced-trees-traversal) and the [postorder](#def-b1-balanced-trees-traversal) sequences of the tree.

**Solution of Exercise 17.1.**

The tree has root 50, children 30 and 70; 30 has children 20 and 40, and 35 is the left child of 40; 70 has children 60 and 80. In order: 20, 30, 35, 40, 50, 60, 70, 80. [Preorder](#def-b1-balanced-trees-traversal): 50, 30, 20, 40, 35, 70, 60, 80. [Postorder](#def-b1-balanced-trees-traversal): 20, 35, 40, 30, 60, 80, 70, 50.

**Exercise 17.2 ★.**

Draw the search tree obtained by inserting 8, 3, 10, 1, 6, 14, 4, 7, 13, and give its height. Then delete 3 and draw the tree again.

**Solution of Exercise 17.2.**

Root 8; left 3 with children 1 and 6, and 6 with children 4 and 7; right 10 with right child 14, whose left child is 13. The height is 3 (paths 8, 3, 6, 4 and 8, 10, 14, 13). Deleting 3, which has two children: its [successor](#def-b1-balanced-trees-ordered) 4, the minimum of its right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), takes its place, and 6 keeps only its right child 7.

**Exercise 17.3 ★.**

Insert 5, 3, 8, 2, 4, 1 into a plain search tree and give the [balance factor](#def-b1-balanced-trees-avl) of every node. Is it an [AVL tree](#def-b1-balanced-trees-avl)? Which [rotation](#def-b1-balanced-trees-rotation) would make it one?

**Solution of Exercise 17.3.**

The tree: 5 with children 3 and 8; 3 with children 2 and 4; 1 the left child of 2. [Balance factors](#def-b1-balanced-trees-avl): 1, 4 and 8 have 0; 2 has $-1 - 0 = -1$; 3 has $0 - 1 = -1$; 5 has $0 - 2 = -2$. It is not an [AVL tree](#def-b1-balanced-trees-avl). The path from 5 to the deepest key goes left twice (LL): a [right rotation](#def-b1-balanced-trees-rotation) at 5 gives root 3, children 2 (with 1) and 5 (with 4 and 8), all [balance factors](#def-b1-balanced-trees-avl) in $\{-1, 0\}$.

**Exercise 17.4 ★.**

Insert S, E, A, R into an empty [left-leaning red-black tree](#def-b1-balanced-trees-rb), and give the tree and the colours after each insertion.

**Solution of Exercise 17.4.**

S: a black root. E: red left child of S. A: red left child of E, two reds in a row: [right rotation](#def-b1-balanced-trees-rotation) at S gives E with red children A and S; the colour flip makes A and S black and E red, and the root is made black. R: larger than E, smaller than S: red left child of S, which is allowed. Final tree: E (black) with children A (black) and S (black), and R (red) the left child of S.

**Exercise 17.5 ★★.**

This deletion lets one child take the place of the deleted node. Explain the output and the memory it leaks.

```c
node *delete(node *t, const char *key) {
    if (t == NULL) return NULL;
    int c = strcmp(key, t->key);
    if (c < 0) t->left = delete(t->left, key);
    else if (c > 0) t->right = delete(t->right, key);
    else {
        node *child = t->left != NULL ? t->left : t->right;  // the child takes the node's place
        free(t);
        return child;
    }
    return t;
}
```

***Listing 17.7.** A shortcut code/bachelor-1/17-balanced-trees/listings/exo_delete_bug.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_delete_bug exo_delete_bug.c bst.c -lm && ./exo_delete_bug
size 7, after deleting Mia: size 3
    Ivy
Eli
    Bea
```

***Output 17.7.** Deleting the root of seven names.*

**Solution of Exercise 17.5.**

Mia has two children; the shortcut returns its left child Eli, and the right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), Tom with Pia and Zoe, is no longer reachable: the tree keeps 3 keys of 6, and the three nodes of the lost [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) are leaked, since nothing points to them any more. The two-child case needs the [successor](#def-b1-balanced-trees-ordered), as in [Listing 17.2](#lst-b1-balanced-trees-delete).

**Exercise 17.6 ★★.**

The [rotation](#def-b1-balanced-trees-rotation) is correct, but its caller is not. The tree held Mia, Eli, Tom, Bea, Ivy and Abe. Explain the output and repair the call.

```c
static node *rotate_right(node *y) {
    node *x = y->left;
    y->left = x->right;
    x->right = y;
    return x;
}
```

***Listing 17.8.** A [right rotation](#def-b1-balanced-trees-rotation) code/bachelor-1/17-balanced-trees/listings/exo_rotate_bug.c*

```
in order after the rotation: Eli Ivy Mia Tom
```

***Output 17.8.** After `rotate_right(t->left);`. Some lines are left out.*

**Solution of Exercise 17.6.**

The [rotation](#def-b1-balanced-trees-rotation) at Eli makes Bea the root of that [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), with left child Abe and right child Eli, and empties Eli’s left link (Bea had no right child). But the call ignores the returned root: Mia still points to Eli, so Bea and Abe are lost and the [in-order traversal](#def-b1-balanced-trees-traversal) prints Eli, Ivy, Mia and Tom. The repair stores the new root in the parent’s link: `t->left = rotate_right(t->left);`, as the AVL code does.

**Exercise 17.7 ★★.**

Write `range_count(t, lo, hi)`, the number of keys $k$ with $\texttt{lo} \leq k \leq \texttt{hi}$, in time $O(h + r)$ where $r$ is the answer, and test it.

**Solution of Exercise 17.7.**

```c
int range_count(const node *t, const char *lo, const char *hi) {
    if (t == NULL) return 0;
    if (strcmp(t->key, lo) < 0) return range_count(t->right, lo, hi);  // all left keys too small
    if (strcmp(t->key, hi) > 0) return range_count(t->left, lo, hi);   // all right keys too large
    return 1 + range_count(t->left, lo, hi) + range_count(t->right, lo, hi);
}
```

*Counting the keys in a range code/bachelor-1/17-balanced-trees/exercises/range_count.c*

A node below `lo` has its whole left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) below `lo`; a node above `hi` its whole right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) above `hi`. So the visited nodes are the ones in the range, plus at most two paths, along the boundaries: $O(h + r)$. The test compares it with a count over a boolean [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) during 20 000 random insertions and deletions.

**Exercise 17.8 ★★.**

A function checks that a tree is a search tree by comparing each node with its two children. Give a tree that it accepts wrongly, then write a correct check that passes bounds down the tree.

**Solution of Exercise 17.8.**

The tree with root 10, left child 5 and 20 the right child of 5 passes the local check (5 < 10, 20 > 5), but 20 lies in the left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of 10. The correct check passes an interval down:

```c
static bool within(const node *t, const char *lo, const char *hi) {  // keys in (lo, hi)
    if (t == NULL) return true;
    if ((lo != NULL && strcmp(t->key, lo) <= 0) || (hi != NULL && strcmp(t->key, hi) >= 0))
        return false;
    return within(t->left, lo, t->key) && within(t->right, t->key, hi);
}

bool is_bst(const node *t) { return within(t, NULL, NULL); }
```

*Checking with bounds code/bachelor-1/17-balanced-trees/exercises/is_bst.c*

A left child must lie between the lower bound of its parent and the parent’s key, a right child between the parent’s key and its upper bound. The test confirms that the local check accepts the counterexample and the correct one rejects it.

**Exercise 17.9 ★★.**

Count the shapes of search trees with $n$ nodes for $n \leq 5$, first by a program that inserts every permutation of $n$ keys and collects the shapes, then by the recurrence $C_n = \sum_{i=0}^{n-1} C_i C_{n-1-i}$. Justify the recurrence.

**Solution of Exercise 17.9.**

The program (`exercises/catalan.py`) finds 1, 1, 2, 5, 14 and 42 shapes for $n = 0, \dots, 5$, as does the recurrence. A shape with $n \geq 1$ nodes is a root with a left shape of $i$ nodes and a right shape of $n - 1 - i$, for $i = 0, \dots, n - 1$, independently: $C_n = \sum_i C_i C_{n-1-i}$. Every shape arises from some insertion order (insert the keys in [preorder](#def-b1-balanced-trees-traversal) of the shape, labelled in order), so the program finds them all.

**Exercise 17.10 ★★★.**

Prove [Theorem 17.12](#thm-b1-balanced-trees-rb-height): show that a [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) whose root has [black height](#def-b1-balanced-trees-rb) $b$ has at least $2^b - 1$ nodes, then that $b \geq (h + 1)/2$ at the root.

**Solution of Exercise 17.10.**

By [structural induction](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-structural), a [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) whose root $x$ has [black height](#def-b1-balanced-trees-rb) $b$ (black nodes on a path from $x$ down, $x$ included if black) has at least $2^b - 1$ nodes. The empty [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) has $b = 0$ and 0 nodes. Each child of $x$ has [black height](#def-b1-balanced-trees-rb) $b - 1$ if $x$ is black and $b$ if $x$ is red, so at least $b - 1$: the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) has at least $1 + 2(2^{b-1} - 1) = 2^b - 1$ nodes. On a longest path, of $h + 1$ nodes from the root, no two consecutive nodes are red and the root is black, so at least $\lceil (h + 1)/2 \rceil$ are black: $b \geq (h +
1)/2$. Hence $n \geq 2^{(h + 1)/2} - 1$, that is $h + 1 \leq 2 \log_2 (n + 1)$. The test checks it after every insertion.

**Exercise 17.11 ★★★.**

Prove that an AVL insertion performs at most one single or double [rotation](#def-b1-balanced-trees-rotation), by showing that the [rotation](#def-b1-balanced-trees-rotation) gives the rebalanced [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) the height it had before the insertion.

**Solution of Exercise 17.11.**

Let $z$ be the lowest node on the path that gets [balance factor](#def-b1-balanced-trees-avl) $-2$ after inserting into its left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) (the mirror case is the same), and $h + 2$ its new height: before the insertion its left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) had height $h$, its right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) $h - 1$, and $z$ height $h + 1$. LL case: the left child $y$ now has height $h + 1$, its left [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) $h$, its right $h -
1$; after a [right rotation](#def-b1-balanced-trees-rotation) at $z$, $z$ has [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of height $h - 1$ and $h - 1$, height $h$, and $y$ has height $h + 1$. LR case: the right [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of $y$, rooted at $x$, has height $h$ and its [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) $h - 1$ and $h - 2$ in some order (both empty when $x$ is the new key, $h = 0$); after the double [rotation](#def-b1-balanced-trees-rotation), $x$ is the root with children $y$ and $z$ of height $h$ each: height $h + 1$. Either way the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) has its height from before the insertion, so no ancestor’s height or [balance factor](#def-b1-balanced-trees-avl) changes, and no other [rotation](#def-b1-balanced-trees-rotation) happens. The test checks at most one [rotation](#def-b1-balanced-trees-rotation) event per insertion on 30 sequences.

**Exercise 17.12 ★★★.**

Write a function that builds a search tree of minimal height from $n$ sorted keys in time $O(n)$, and prove that its height is $\lfloor \log_2 n \rfloor$.

**Solution of Exercise 17.12.**

```c
node *from_sorted(const char **keys, int lo, int hi) {  // keys[lo..hi), sorted
    if (lo >= hi) return NULL;
    int mid = lo + (hi - lo) / 2;  // the middle key is the root
    node *t = malloc(sizeof *t);
    if (t == NULL) exit(1);
    *t = (node){keys[mid], mid, from_sorted(keys, lo, mid), from_sorted(keys, mid + 1, hi)};
    return t;
}
```

*The middle key as the root code/bachelor-1/17-balanced-trees/exercises/from_sorted.c*

Each key becomes one node, in constant time: $O(n)$. The two halves have $\lfloor (n - 1)/2 \rfloor$ and $\lceil (n -
1)/2 \rceil$ keys. By strong induction the height is $H(n) = \lfloor \log_2 n \rfloor$: $H(1) = 0$, and $H(n) = 1 +
H(\lceil (n-1)/2 \rceil) = 1 + \lfloor \log_2 \lfloor n/2 \rfloor \rfloor = \lfloor \log_2 n \rfloor$, since $\lceil
(n - 1)/2 \rceil = \lfloor n/2 \rfloor$. The test checks the height for every $n \leq 400$.

## 17.8 Problem: Indexing the library catalogue

**Problem 17.1.**

Weekend problem — Indexing the library catalogue

The town library has 80 titles, numbered in its catalogue. [Output 17.2](#out-b1-balanced-trees-heights) gives the heights of the trees built from the first $n$ titles by inserting them in catalogue order, in alphabetical order and in 1000 random orders, into a plain search tree, and in catalogue order into an [AVL tree](#def-b1-balanced-trees-avl) and a [left-leaning red-black tree](#def-b1-balanced-trees-rb); its last three lines count the [rotations](#def-b1-balanced-trees-rotation) and give the [black height](#def-b1-balanced-trees-rb). [Output 17.4](#out-b1-balanced-trees-minimal) counts minimal [AVL trees](#def-b1-balanced-trees-avl).

**Part I — Insertion order.**

1. Why is the height of the plain tree exactly $n - 1$ in the alphabetical column?
2. In that tree, how many comparisons does a successful search make on average, for $n = 80$ ?
3. How many comparisons does building it take?
4. Compare the catalogue column with the random orders. What does it suggest about the catalogue numbers?
5. Compare the heights at $n = 80$ with the lower bound $\lfloor \log_2 80 \rfloor$ .
6. A library adds its new titles each year in alphabetical order. Give two ways to keep its searches fast.

**Part II — AVL insertion.**

7. The alphabetical order needs 73 single [rotations](#def-b1-balanced-trees-rotation) and no double [rotation](#def-b1-balanced-trees-rotation) . Why can increasing keys never need a double [rotation](#def-b1-balanced-trees-rotation) ?
8. In catalogue order, how many of the 80 insertions rotate? What does an insertion cost in all?
9. Insert 3, 1, 2 into an empty [AVL tree](#def-b1-balanced-trees-avl) : which case arises, and what are the two [rotations](#def-b1-balanced-trees-rotation) ?
10. Why must the stored heights be updated on the way back up, and why does each update cost $O(1)$ ?
11. The [AVL tree](#def-b1-balanced-trees-avl) of the 80 titles in catalogue order has height 7. Is a taller [AVL tree](#def-b1-balanced-trees-avl) with 80 nodes possible?
12. A deletion can need a [rotation](#def-b1-balanced-trees-rotation) at every level of the path. Why does the argument of [Exercise 17.11](#exo-b1-balanced-trees-11) fail for deletions?

**Part III — Colours and black height.**

13. The [red-black tree](#def-b1-balanced-trees-rb) of the 80 titles has height 7 and [black height](#def-b1-balanced-trees-rb) 5. Check [Theorem 17.12](#thm-b1-balanced-trees-rb-height) and the bound $n \geq 2^b - 1$ .
14. In [Output 17.5](#out-b1-balanced-trees-llrb-demo) , list the red nodes and the nodes of the corresponding 2-3 tree.
15. Show that a [left-leaning red-black tree](#def-b1-balanced-trees-rb) of [black height](#def-b1-balanced-trees-rb) $b$ has between $2^b - 1$ and $3^b - 1$ keys.
16. Which [black heights](#def-b1-balanced-trees-rb) are possible for 80 keys?
17. Why does a new key enter the tree as a red node?
18. Compare the guarantees and the [rotation](#def-b1-balanced-trees-rotation) counts of AVL and [red-black trees](#def-b1-balanced-trees-rb) , and say which suits a [dictionary](https://one-course.com/books/computer-science/3/en/chapter/16-hash-tables#def-b1-hash-tables-dictionary) with many deletions.

**Part IV — Minimal AVL trees.**

19. Prove $N(h) = N(h - 1) + N(h - 2) + 1$ for $h \geq 2$ , with $N(0) = 1$ and $N(1) = 2$ .
20. Prove $N(h) = F_{h+3} - 1$ by induction.
21. Prove $F_k \geq \varphi^{k-2}$ for $k \geq 1$ , using $\varphi^2 = \varphi + 1$ .
22. Deduce $h \leq \log_\varphi (n + 1) - 1$ for every [AVL tree](#def-b1-balanced-trees-avl) with $n$ nodes.
23. Compute this bound for $n = 80$ , and compare with the largest height of [Output 17.4](#out-b1-balanced-trees-minimal) and with the measured AVL height.
24. State the named result of the problem, *minimal [AVL trees](#def-b1-balanced-trees-avl) are Fibonacci trees* , with the height bound it gives for the 80 titles.

**Solution of Problem 17.1.**

**1.** Each new title is larger than all the previous ones: the search goes right at every node, and the new node becomes the right child of the deepest one. The tree is a path of $n$ nodes.

**2.** The title at depth $d$ costs $d + 1$ comparisons: $(1 + 2 + \dots + 80)/80 = 40.5$.

**3.** The $i$-th insertion compares with the $i - 1$ titles already there: $0 + 1 + \dots + 79 = 3160$.

**4.** 11 against an average of 11.39 at $n = 80$, and close all along: the catalogue numbers are unrelated to the alphabetical order of the titles, and behave like a random order.

**5.** $\lfloor \log_2 80 \rfloor = 6$: catalogue order 11, alphabetical 79, random 11.39 on average, AVL and red-black 7.

**6.** Use a balanced tree, AVL or red-black; or rebuild a tree of minimal height from the sorted list each year ([Exercise 17.12](#exo-b1-balanced-trees-12)).

**7.** The new key is always the rightmost: the path from any unbalanced node to it goes right twice, the RR case, repaired by a single left [rotation](#def-b1-balanced-trees-rotation).

**8.** $22 + 11 = 33$, since an insertion makes at most one [rotation](#def-b1-balanced-trees-rotation) event. An insertion costs $O(\log n)$: the descent and the way back up, $O(h)$ with $h \leq 1.44 \log_2 (n + 2)$, and a [rotation](#def-b1-balanced-trees-rotation) in $O(1)$.

**9.** 2 goes to the right of 1, and 3 has [balance factor](#def-b1-balanced-trees-avl) $-2$ with its left child 1 at $+1$: case LR. A left [rotation](#def-b1-balanced-trees-rotation) at 1 makes 2 the left child of 3 with left child 1 (case LL), and a [right rotation](#def-b1-balanced-trees-rotation) at 3 gives root 2, children 1 and 3.

**10.** The [balance factors](#def-b1-balanced-trees-avl) are computed from the heights, which change only on the path of the insertion, and the height of a node is $1 + \max$ of its children’s stored heights: $O(1)$ per node.

**11.** No: $N(8) = 88 > 80$, so an [AVL tree](#def-b1-balanced-trees-avl) with 80 nodes has height at most 7. This one is as tall as possible.

**12.** After a deletion, the [rotation](#def-b1-balanced-trees-rotation) can leave the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) one level lower than before, which changes the [balance factor](#def-b1-balanced-trees-avl) of its parent; the imbalance can then move up level by level.

**13.** $h + 1 = 8 \leq 2 \log_2 81 \approx 12.7$, and $2^5 - 1 = 31 \leq 80$.

**14.** The red nodes are F and I. The 2-3 tree has root D, children B and (F, H), and leaves A, C, E, G and (I, J).

**15.** The 2-3 tree has $b$ levels and all its leaves at the same depth. With only one-key nodes it holds $1 + 2 +
\dots + 2^{b-1} = 2^b - 1$ keys; with only two-key nodes, level $i$ has $3^i$ nodes of 2 keys: $2(1 + 3 + \dots +
3^{b-1}) = 3^b - 1$.

**16.** $2^b - 1 \leq 80$ gives $b \leq 6$; $3^b - 1 \geq 80$ gives $b \geq 4$: $b$ is 4, 5 or 6. The tree has 5.

**17.** A red node does not change any [black height](#def-b1-balanced-trees-rb); only the rule on red nodes can be broken, and the local repairs fix it on the way up. A black node would break the equal [black heights](#def-b1-balanced-trees-rb), which no local repair can fix.

**18.** [AVL trees](#def-b1-balanced-trees-avl) are lower ($1.44 \log_2 n$ against $2 \log_2 n$), so searches are slightly faster; an insertion makes at most one [rotation](#def-b1-balanced-trees-rotation) event in the [AVL tree](#def-b1-balanced-trees-avl) and in the classic [red-black tree](#def-b1-balanced-trees-rb) (the left-leaning variant of this chapter may rotate at several levels on the way up), but an AVL deletion may rotate at every level, a classic red-black deletion at most a constant number of times. With many deletions, the classic [red-black tree](#def-b1-balanced-trees-rb).

**19.** A tree of height $h \geq 2$ has a [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of height $h - 1$; the other has height $h - 1$ or $h - 2$, and the fewest nodes come with $h - 2$; each [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) must itself be a smallest [AVL tree](#def-b1-balanced-trees-avl) of its height, or a smaller one could replace it. So $N(h) = 1 + N(h - 1) + N(h - 2)$. $N(0) = 1$ (a root) and $N(1) = 2$ (a root and a child).

**20.** $N(0) = 1 = F_3 - 1$, $N(1) = 2 = F_4 - 1$, and $N(h) = (F_{h+2} - 1) + (F_{h+1} - 1) + 1 = F_{h+3} - 1$.

**21.** $F_1 = 1 \geq \varphi^{-1}$ and $F_2 = 1 \geq \varphi^0$; then $F_{k+2} = F_{k+1} + F_k \geq \varphi^{k-1} +
\varphi^{k-2} = \varphi^{k-2}(\varphi + 1) = \varphi^k$.

**22.** $n \geq N(h) = F_{h+3} - 1 \geq \varphi^{h+1} - 1$, so $h + 1 \leq \log_\varphi (n + 1)$.

**23.** $\log_\varphi 81 = \ln 81 / \ln \varphi \approx 4.394/0.4812 \approx 9.13$, so $h \leq 8.13$, that is $h \leq
8$. The exact largest height is 7 ($N(7) = 54 \leq 80 < N(8) = 88$), and the measured [AVL tree](#def-b1-balanced-trees-avl) reaches it.

**24.** *Minimal [AVL trees](#def-b1-balanced-trees-avl) are Fibonacci trees*: the smallest [AVL tree](#def-b1-balanced-trees-avl) of height $h$ is a root with smallest [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of heights $h - 1$ and $h - 2$, and it has $N(h) = F_{h+3} - 1$ nodes (questions 19 and 20; checked up to $h = 20$, 28 656 nodes). Hence every [AVL tree](#def-b1-balanced-trees-avl) with $n$ nodes has height at most $\log_\varphi (n + 1) - 1 < 1.45 \log_2
(n + 2)$: for the 80 titles, at most 8 by the bound and at most 7 exactly, the height measured in catalogue order.
