علوم الحاسوب · الكتاب 3 · السنة الجامعية 1

University Computer Science — Year 1

هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.

University Computer Science — Year 1 · السنة الجامعية 1

17Binary 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. 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 and red-black trees.

You already know

A binary tree is empty or a root with a left and a right subtree; its height is the number of edges on a longest path from the root down, −1-1 for the empty tree (Definition 11.4). Properties of trees are proved by structural induction (Definition 11.5). A dictionary associates values with keys (Definition 16.1).

17.1 Binary search trees

Definition 17.1 (Binary search tree)

A binary search tree is a binary tree whose nodes hold keys from an ordered set, with the search-tree property: at every node, the keys of the left subtree are smaller than the node’s key, and the keys of the right subtree 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)O(h) for a tree of height hh. Insertion searches, and puts the new node where the search fell off the tree.

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 visits the left subtree, then the root, then the right subtree; the preorder visits the root first, the postorder last.

Proposition 17.3 (In-order is sorted)

The in-order traversal of a binary search tree visits its keys in increasing order.

Proof. By structural induction. The empty tree visits nothing. For a root rr with subtrees LL and RR, the traversal visits the keys of LL in increasing order (hypothesis), all smaller than rr (search-tree property), then rr, then the keys of RR in increasing order, all larger than rr. ∎

Definition 17.4 (Ordered dictionary, successor)

An ordered dictionary is a dictionary whose keys are ordered, with the further operations minimum, maximum, floor (the largest key at most kk), ceiling, successor (the smallest key larger than kk), and the listing of the keys between two bounds.

A 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 above); the deletion of a node with two children.

Deletion has three cases. A leaf is removed. A node with one child is replaced by that child. A node with two children takes the key of its successor, the minimum of its right subtree, which has no left child, and that successor is deleted from the right subtree by one of the first two cases.

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 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.
Left: the tree of Output 17.1 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.

17.2 Height bounds

Every operation of the previous section costs Θ(h)\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 with n≥1n \geq 1 nodes has height hh with ⌊log⁡2n⌋≤h≤n−1\lfloor \log_2 n \rfloor \leq h \leq n - 1.

Proof. A longest path holds h+1h + 1 nodes, all distinct, so n≥h+1n \geq h + 1. Depth dd holds at most 2d2^d nodes, so n≤1+2+⋯+2h=2h+1−1<2h+1n \leq 1 + 2 + \dots + 2^h = 2^{h+1} - 1 < 2^{h+1}, and log⁡2n<h+1\log_2 n < h + 1, that is ⌊log⁡2n⌋≤h\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−1n - 1, and it is a linked list.

Inserting keys in increasing order builds a degenerate tree: 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 nn 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.
Heights from Output 17.2. The alphabetical order climbs as n−1n - 1 and leaves the chart at n=27n = 27; random orders grow slowly; the AVL tree stays within one or two of the lower bound.

A random order of insertion gives, on average, a height of order log⁡n\log n; the average depth of a node is about 2ln⁡n≈1.39log⁡2n2 \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)O(\log n) for every order, by repairing the tree after each insertion with rotations.

17.3 Rotations

Definition 17.7 (Rotation)

A right rotation at a node yy with left child xx makes xx the root of the subtree, yy its right child, and the former right subtree of xx the left subtree of yy. 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.
A rotation changes three links. The in-order sequence is A,x,B,y,CA, x, B, y, C on both sides; the subtree BB (shaded) changes parent; AA moves up a level and CC down a level.

Proposition 17.8 (Rotations preserve the order)

A rotation of a binary search tree yields a binary search tree with the same keys and the same in-order sequence.

Proof. Before a right rotation, the in-order sequence of the subtree is A,x,B,y,CA, x, B, y, C, where AA, BB and CC stand for the sequences of the three subtrees: xx is the left child of yy, AA and BB its subtrees. After it, xx is the root with left subtree AA and right subtree yy, whose subtrees are BB and CC: the sequence is again A,x,B,y,CA, x, B, y, C. The rest of the tree, outside the subtree, is unchanged, and the subtree’s set of keys too, so the property holds everywhere. ∎

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, 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 minus the height of its left subtree. An AVL tree is a binary search tree in which every node has balance factor −1-1, 0 or 1.

AVL trees 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 ±2\pm 2. Four cases repair it, named after the path from the unbalanced node to the new key: a single rotation when the path goes twice the same way (LL or RR), a double rotation when it turns (LR or RL), which first rotates the child the other way.

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.
Two of the four rebalancing cases, on three keys; the new key is shaded. The node 3 has balance factor −2-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.
$ 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; balance factors in parentheses.

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

Theorem 17.10 (Height of an AVL tree)

An AVL tree with nn nodes has height h≤log⁡φ(n+1)−1<1.45log⁡2(n+2)h \leq \log_\varphi (n + 1) - 1 < 1.45 \log_2 (n + 2), where φ=(1+5)/2\varphi = (1 + \sqrt 5)/2.

Proof. Let N(h)N(h) be the smallest number of nodes of an AVL tree of height hh: N(0)=1N(0) = 1, N(1)=2N(1) = 2. A smallest tree of height h≥2h \geq 2 has one subtree of height h−1h - 1 and, since the balance factor is at most 1 in absolute value and the tree is smallest, the other of height h−2h - 2, both smallest themselves: N(h)=N(h−1)+N(h−2)+1N(h) = N(h - 1) + N(h - 2) + 1. With the Fibonacci numbers F0=0F_0 = 0, F1=1F_1 = 1, Fk+2=Fk+1+FkF_{k+2} = F_{k+1} + F_k, induction gives N(h)=Fh+3−1N(h) = F_{h+3} - 1, and Fk≥φk−2F_k \geq \varphi^{k-2} for k≥1k \geq 1 (problem, Part IV). So n≥N(h)≥φh+1−1n \geq N(h) \geq \varphi^{h+1} - 1, and h+1≤log⁡φ(n+1)h + 1 \leq \log_\varphi (n + 1). Finally 1/log⁡2φ≈1.44041/\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, 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 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 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 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 is then a 2-3 tree, whose nodes hold one or two keys and whose empty subtrees 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.

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 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.
Left: the left-leaning red-black tree of Output 17.5, 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.

Theorem 17.12 (Height of a red-black tree)

A red-black tree with nn nodes has height hh with h+1≤2log⁡2(n+1)h + 1 \leq 2 \log_2 (n + 1).

The proof (Exercise 17.10) counts at least 2b−12^b - 1 nodes below a node of black height bb, and at least one black node out of two on any path. The bound is weaker than the AVL tree’s, 22 against 1.441.44, but the repairs are simpler, and deletion needs at most a constant number of rotations in the classic version. The standard libraries of C++ and Java implement their ordered maps as red-black trees; 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 are not part of it, since they are only meaningful in one address space.

A preorder traversal that writes a marker for each empty subtree describes the shape completely: reading it back, the first item is the root, then comes the left subtree, written in the same way, then the right one.

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 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), and it is the better file format: it does not depend on the shape, which is an accident of the insertion order. The preorder 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 and the postorder sequences of the tree.

Solution

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: 50, 30, 20, 40, 35, 70, 60, 80. Postorder: 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

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 4, the minimum of its right subtree, 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 of every node. Is it an AVL tree? Which rotation would make it one?

Solution

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: 1, 4 and 8 have 0; 2 has −1−0=−1-1 - 0 = -1; 3 has 0−1=−10 - 1 = -1; 5 has 0−2=−20 - 2 = -2. It is not an AVL tree. The path from 5 to the deepest key goes left twice (LL): a right rotation at 5 gives root 3, children 2 (with 1) and 5 (with 4 and 8), all balance factors in {−1,0}\{-1, 0\}.

Exercise 17.4 ★

Insert S, E, A, R into an empty left-leaning red-black tree, and give the tree and the colours after each insertion.

Solution

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 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.

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

Solution of Exercise 17.5.

Mia has two children; the shortcut returns its left child Eli, and the right subtree, Tom with Pia and Zoe, is no longer reachable: the tree keeps 3 keys of 6, and the three nodes of the lost subtree are leaked, since nothing points to them any more. The two-child case needs the successor, as in Listing 17.2.

Exercise 17.6 ★★

The 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.

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 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

Solution of Exercise 17.6.

The rotation at Eli makes Bea the root of that subtree, 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 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 kk with lo≤k≤hi\texttt{lo} \leq k \leq \texttt{hi}, in time O(h+r)O(h + r) where rr is the answer, and test it.

Solution

Solution of Exercise 17.7.

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 below lo; a node above hi its whole right subtree above hi. So the visited nodes are the ones in the range, plus at most two paths, along the boundaries: O(h+r)O(h + r). The test compares it with a count over a boolean 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

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 of 10. The correct check passes an interval down:

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 nn nodes for n≤5n \leq 5, first by a program that inserts every permutation of nn keys and collects the shapes, then by the recurrence Cn=∑i=0n−1CiCn−1−iC_n = \sum_{i=0}^{n-1} C_i C_{n-1-i}. Justify the recurrence.

Solution

Solution of Exercise 17.9.

The program (exercises/catalan.py) finds 1, 1, 2, 5, 14 and 42 shapes for n=0,…,5n = 0, \dots, 5, as does the recurrence. A shape with n≥1n \geq 1 nodes is a root with a left shape of ii nodes and a right shape of n−1−in - 1 - i, for i=0,…,n−1i = 0, \dots, n - 1, independently: Cn=∑iCiCn−1−iC_n = \sum_i C_i C_{n-1-i}. Every shape arises from some insertion order (insert the keys in preorder of the shape, labelled in order), so the program finds them all.

Exercise 17.10 ★★★

Prove Theorem 17.12: show that a subtree whose root has black height bb has at least 2b−12^b - 1 nodes, then that b≥(h+1)/2b \geq (h + 1)/2 at the root.

Solution

Solution of Exercise 17.10.

By structural induction, a subtree whose root xx has black height bb (black nodes on a path from xx down, xx included if black) has at least 2b−12^b - 1 nodes. The empty subtree has b=0b = 0 and 0 nodes. Each child of xx has black height b−1b - 1 if xx is black and bb if xx is red, so at least b−1b - 1: the subtree has at least 1+2(2b−1−1)=2b−11 + 2(2^{b-1} - 1) = 2^b - 1 nodes. On a longest path, of h+1h + 1 nodes from the root, no two consecutive nodes are red and the root is black, so at least ⌈(h+1)/2⌉\lceil (h + 1)/2 \rceil are black: b≥(h+1)/2b \geq (h + 1)/2. Hence n≥2(h+1)/2−1n \geq 2^{(h + 1)/2} - 1, that is h+1≤2log⁡2(n+1)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, by showing that the rotation gives the rebalanced subtree the height it had before the insertion.

Solution

Solution of Exercise 17.11.

Let zz be the lowest node on the path that gets balance factor −2-2 after inserting into its left subtree (the mirror case is the same), and h+2h + 2 its new height: before the insertion its left subtree had height hh, its right subtree h−1h - 1, and zz height h+1h + 1. LL case: the left child yy now has height h+1h + 1, its left subtree hh, its right h−1h - 1; after a right rotation at zz, zz has subtrees of height h−1h - 1 and h−1h - 1, height hh, and yy has height h+1h + 1. LR case: the right subtree of yy, rooted at xx, has height hh and its subtrees h−1h - 1 and h−2h - 2 in some order (both empty when xx is the new key, h=0h = 0); after the double rotation, xx is the root with children yy and zz of height hh each: height h+1h + 1. Either way the subtree has its height from before the insertion, so no ancestor’s height or balance factor changes, and no other rotation happens. The test checks at most one rotation event per insertion on 30 sequences.

Exercise 17.12 ★★★

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

Solution

Solution of Exercise 17.12.

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)O(n). The two halves have ⌊(n−1)/2⌋\lfloor (n - 1)/2 \rfloor and ⌈(n−1)/2⌉\lceil (n - 1)/2 \rceil keys. By strong induction the height is H(n)=⌊log⁡2n⌋H(n) = \lfloor \log_2 n \rfloor: H(1)=0H(1) = 0, and H(n)=1+H(⌈(n−1)/2⌉)=1+⌊log⁡2⌊n/2⌋⌋=⌊log⁡2n⌋H(n) = 1 + H(\lceil (n-1)/2 \rceil) = 1 + \lfloor \log_2 \lfloor n/2 \rfloor \rfloor = \lfloor \log_2 n \rfloor, since ⌈(n−1)/2⌉=⌊n/2⌋\lceil (n - 1)/2 \rceil = \lfloor n/2 \rfloor. The test checks the height for every n≤400n \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 gives the heights of the trees built from the first nn 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 and a left-leaning red-black tree; its last three lines count the rotations and give the black height. Output 17.4 counts minimal AVL trees.

Part I — Insertion order.

  1. Why is the height of the plain tree exactly n−1n - 1 in the alphabetical column?
  2. In that tree, how many comparisons does a successful search make on average, for n=80n = 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=80n = 80 with the lower bound ⌊log⁡280⌋\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.

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

Part III — Colours and black height.

  1. The red-black tree of the 80 titles has height 7 and black height 5. Check Theorem 17.12 and the bound n≥2b−1n \geq 2^b - 1.
  2. In Output 17.5, list the red nodes and the nodes of the corresponding 2-3 tree.
  3. Show that a left-leaning red-black tree of black height bb has between 2b−12^b - 1 and 3b−13^b - 1 keys.
  4. Which black heights are possible for 80 keys?
  5. Why does a new key enter the tree as a red node?
  6. Compare the guarantees and the rotation counts of AVL and red-black trees, and say which suits a dictionary with many deletions.

Part IV — Minimal AVL trees.

  1. Prove N(h)=N(h−1)+N(h−2)+1N(h) = N(h - 1) + N(h - 2) + 1 for h≥2h \geq 2, with N(0)=1N(0) = 1 and N(1)=2N(1) = 2.
  2. Prove N(h)=Fh+3−1N(h) = F_{h+3} - 1 by induction.
  3. Prove Fk≥φk−2F_k \geq \varphi^{k-2} for k≥1k \geq 1, using φ2=φ+1\varphi^2 = \varphi + 1.
  4. Deduce h≤log⁡φ(n+1)−1h \leq \log_\varphi (n + 1) - 1 for every AVL tree with nn nodes.
  5. Compute this bound for n=80n = 80, and compare with the largest height of Output 17.4 and with the measured AVL height.
  6. State the named result of the problem, minimal AVL trees are Fibonacci trees, with the height bound it gives for the 80 titles.
Solution

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 nn nodes.

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

3. The ii-th insertion compares with the i−1i - 1 titles already there: 0+1+⋯+79=31600 + 1 + \dots + 79 = 3160.

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

5. ⌊log⁡280⌋=6\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).

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.

8. 22+11=3322 + 11 = 33, since an insertion makes at most one rotation event. An insertion costs O(log⁡n)O(\log n): the descent and the way back up, O(h)O(h) with h≤1.44log⁡2(n+2)h \leq 1.44 \log_2 (n + 2), and a rotation in O(1)O(1).

9. 2 goes to the right of 1, and 3 has balance factor −2-2 with its left child 1 at +1+1: case LR. A left rotation at 1 makes 2 the left child of 3 with left child 1 (case LL), and a right rotation at 3 gives root 2, children 1 and 3.

10. The balance factors are computed from the heights, which change only on the path of the insertion, and the height of a node is 1+max⁡1 + \max of its children’s stored heights: O(1)O(1) per node.

11. No: N(8)=88>80N(8) = 88 > 80, so an AVL tree with 80 nodes has height at most 7. This one is as tall as possible.

12. After a deletion, the rotation can leave the subtree one level lower than before, which changes the balance factor of its parent; the imbalance can then move up level by level.

13. h+1=8≤2log⁡281≈12.7h + 1 = 8 \leq 2 \log_2 81 \approx 12.7, and 25−1=31≤802^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 bb levels and all its leaves at the same depth. With only one-key nodes it holds 1+2+⋯+2b−1=2b−11 + 2 + \dots + 2^{b-1} = 2^b - 1 keys; with only two-key nodes, level ii has 3i3^i nodes of 2 keys: 2(1+3+⋯+3b−1)=3b−12(1 + 3 + \dots + 3^{b-1}) = 3^b - 1.

16. 2b−1≤802^b - 1 \leq 80 gives b≤6b \leq 6; 3b−1≥803^b - 1 \geq 80 gives b≥4b \geq 4: bb is 4, 5 or 6. The tree has 5.

17. A red node does not change any black height; 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, which no local repair can fix.

18. AVL trees are lower (1.44log⁡2n1.44 \log_2 n against 2log⁡2n2 \log_2 n), so searches are slightly faster; an insertion makes at most one rotation event in the AVL tree and in the classic red-black tree (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.

19. A tree of height h≥2h \geq 2 has a subtree of height h−1h - 1; the other has height h−1h - 1 or h−2h - 2, and the fewest nodes come with h−2h - 2; each subtree must itself be a smallest AVL tree of its height, or a smaller one could replace it. So N(h)=1+N(h−1)+N(h−2)N(h) = 1 + N(h - 1) + N(h - 2). N(0)=1N(0) = 1 (a root) and N(1)=2N(1) = 2 (a root and a child).

20. N(0)=1=F3−1N(0) = 1 = F_3 - 1, N(1)=2=F4−1N(1) = 2 = F_4 - 1, and N(h)=(Fh+2−1)+(Fh+1−1)+1=Fh+3−1N(h) = (F_{h+2} - 1) + (F_{h+1} - 1) + 1 = F_{h+3} - 1.

21. F1=1≥φ−1F_1 = 1 \geq \varphi^{-1} and F2=1≥φ0F_2 = 1 \geq \varphi^0; then Fk+2=Fk+1+Fk≥φk−1+φk−2=φk−2(φ+1)=φkF_{k+2} = F_{k+1} + F_k \geq \varphi^{k-1} + \varphi^{k-2} = \varphi^{k-2}(\varphi + 1) = \varphi^k.

22. n≥N(h)=Fh+3−1≥φh+1−1n \geq N(h) = F_{h+3} - 1 \geq \varphi^{h+1} - 1, so h+1≤log⁡φ(n+1)h + 1 \leq \log_\varphi (n + 1).

23. log⁡φ81=ln⁡81/ln⁡φ≈4.394/0.4812≈9.13\log_\varphi 81 = \ln 81 / \ln \varphi \approx 4.394/0.4812 \approx 9.13, so h≤8.13h \leq 8.13, that is h≤8h \leq 8. The exact largest height is 7 (N(7)=54≤80<N(8)=88N(7) = 54 \leq 80 < N(8) = 88), and the measured AVL tree reaches it.

24. Minimal AVL trees are Fibonacci trees: the smallest AVL tree of height hh is a root with smallest subtrees of heights h−1h - 1 and h−2h - 2, and it has N(h)=Fh+3−1N(h) = F_{h+3} - 1 nodes (questions 19 and 20; checked up to h=20h = 20, 28 656 nodes). Hence every AVL tree with nn nodes has height at most log⁡φ(n+1)−1<1.45log⁡2(n+2)\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.

المصطلحات المعرَّفة في هذا الفصل

عرض كل المصطلحات (1050) في المسرد