---
title: "Trees and Binary Search Trees"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 25
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/25-trees-and-binary-search-trees
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 25 — Trees and Binary Search Trees

“I am thinking of a number between $1$ and $100$.” The best first guess is $50$; after “smaller”, $25$; after “larger”, $37$. Every game follows one path through a fixed set of questions: $50$ at the top, $25$ and $75$ below it, then $12$, $37$, $62$, $87$, and so on. Drawn out, these questions form a [tree](#def-g12-trees-tree), and the length of the longest path is the number of guesses the game can need.

This chapter names the parts of a [tree](#def-g12-trees-tree), builds [binary trees](#def-g12-trees-binary-tree) with a class, visits their [nodes](#def-g12-trees-tree) in four orders, and stores keys in [binary search trees](#def-g12-trees-bst), where finding a key costs as many steps as the [tree](#def-g12-trees-tree) is tall. Then it asks how tall such a [tree](#def-g12-trees-tree) grows, and measures it.

**You already know.**

A [recursive function](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#def-g12-recursion-recursion) calls itself on smaller inputs, and is proved by induction (chapter [22](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#ch-g12-recursion)). A queue gives back its elements in the order they came (chapter [24](https://one-course.com/books/computer-science/2/en/chapter/24-linked-lists-stacks-and-queues#ch-g12-lists-stacks-queues)). Folders inside folders (Book 1, grade 3) and the nested elements of a web page (Book 1, grade 9) are [trees](#def-g12-trees-tree).

## 25.1 Vocabulary

**Definition 25.1 (Tree, node, root, leaf, parent, child, subtree).**

A *tree* is a set of *nodes* linked so that one node, the *root*, has no parent, and every other node has exactly one *parent*; a node is a *child* of its parent. A node with no child is a *leaf*. A node together with all the nodes below it forms a *subtree*.

**Definition 25.2 (Depth, height, size).**

The *depth* of a [node](#def-g12-trees-tree) is the number of links from the [root](#def-g12-trees-tree) to it: the [root](#def-g12-trees-tree) has depth $0$. The *height* of a [tree](#def-g12-trees-tree) is the largest depth of its [nodes](#def-g12-trees-tree); a [tree](#def-g12-trees-tree) of one [node](#def-g12-trees-tree) has height $0$, and by convention the empty [tree](#def-g12-trees-tree) has height $-1$. The *size* of a [tree](#def-g12-trees-tree) is its number of [nodes](#def-g12-trees-tree).

![A tree of size 7 and height 3. A is the root; D, G and F are the leaves (shaded); B is the parent of D and E. The dashed line surrounds the subtree of root B: size 4, height 2.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-trees/fig-3fa6c8be4ac0.svg)

*A [tree](#def-g12-trees-tree) of [size](#def-g12-trees-height) $7$ and [height](#def-g12-trees-height) $3$. A is the [root](#def-g12-trees-tree); D, G and F are the leaves (shaded); B is the [parent](#def-g12-trees-tree) of D and E. The dashed line surrounds the [subtree](#def-g12-trees-tree) of [root](#def-g12-trees-tree) B: [size](#def-g12-trees-height) $4$, [height](#def-g12-trees-height) $2$.*

## 25.2 Binary trees

**Definition 25.3 (Binary tree).**

A *binary tree* is either empty, or a [node](#def-g12-trees-tree) holding a value and two binary [trees](#def-g12-trees-tree), its left [subtree](#def-g12-trees-tree) and its right [subtree](#def-g12-trees-tree).

The definition is recursive, and so are the functions on [binary trees](#def-g12-trees-binary-tree): each one says what to do with the empty [tree](#def-g12-trees-tree), and how to combine the answers of the two [subtrees](#def-g12-trees-tree). In Python the empty [tree](#def-g12-trees-tree) is `None`.

```python
"""Binary trees: None is the empty tree, a Node has a value and two subtrees."""


class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


def size(t):
    if t is None:
        return 0
    return 1 + size(t.left) + size(t.right)


def height(t):
    if t is None:
        return -1                  # so that a single node has height 0
    return 1 + max(height(t.left), height(t.right))


def leaves(t):
    if t is None:
        return 0
    if t.left is None and t.right is None:
        return 1
    return leaves(t.left) + leaves(t.right)
```

***Listing 25.1.** [Binary trees](#def-g12-trees-binary-tree): a class of [nodes](#def-g12-trees-tree), and three recursive measures. code/grade-12/04-trees/listings/node.py*

```python
from node import Node, height, leaves, size

#        A
#      /   \
#     B     C
#    / \     \
#   D   E     F
#      /
#     G
t = Node("A", Node("B", Node("D"), Node("E", Node("G"))), Node("C", None, Node("F")))
print("size", size(t), "| height", height(t), "| leaves", leaves(t))
print("subtree B: size", size(t.left), "| height", height(t.left))
print("single node: height", height(Node("X")), "| empty tree: height", height(None))
```

***Listing 25.2.** The [tree](#def-g12-trees-tree) of the figure. code/grade-12/04-trees/listings/size_height.py*

```
$ python size_height.py
size 7 | height 3 | leaves 3
subtree B: size 4 | height 2
single node: height 0 | empty tree: height -1
```

***Output 25.1.** The numbers read on the figure, and the two conventions for small [trees](#def-g12-trees-tree).*

**Theorem 25.4 (Size and height).**

A [binary tree](#def-g12-trees-binary-tree) of [height](#def-g12-trees-height) $h \ge 0$ has a [size](#def-g12-trees-height) $n$ with $h + 1 \le n \le 2^{h+1} - 1$.

The lower bound holds because a path from the [root](#def-g12-trees-tree) to the deepest [node](#def-g12-trees-tree) already holds $h + 1$ [nodes](#def-g12-trees-tree). For the upper bound, [depth](#def-g12-trees-height) $d$ holds at most $2^d$ [nodes](#def-g12-trees-tree), since each [node](#def-g12-trees-tree) has at most two children, and $1 + 2 + 4 + \dots + 2^h = 2^{h+1} - 1$. Exercise [25.12](#exo-g12-trees-12) proves it again, by induction on the recursive definition. Turned around: a [binary tree](#def-g12-trees-binary-tree) of $n$ [nodes](#def-g12-trees-tree) has a [height](#def-g12-trees-height) of at least the number of times $n + 1$ can be halved, minus one; $1023$ [nodes](#def-g12-trees-tree) need a [height](#def-g12-trees-height) of at least $9$.

## 25.3 Traversals

**Definition 25.5 (Traversal, preorder, inorder, postorder, breadth-first order).**

A *traversal* of a [tree](#def-g12-trees-tree) visits each [node](#def-g12-trees-tree) once. In *preorder*, a [node](#def-g12-trees-tree) is visited before its left and right [subtrees](#def-g12-trees-tree); in *inorder*, between them; in *postorder*, after them. In *breadth-first order*, [nodes](#def-g12-trees-tree) are visited level by level, from the [root](#def-g12-trees-tree) down, from left to right in each level.

```python
from collections import deque

from node import Node


def preorder(t):                      # the node, then its left, then its right
    return [] if t is None else [t.value] + preorder(t.left) + preorder(t.right)


def inorder(t):                       # left, the node, right
    return [] if t is None else inorder(t.left) + [t.value] + inorder(t.right)


def postorder(t):                     # left, right, the node last
    return [] if t is None else postorder(t.left) + postorder(t.right) + [t.value]


def breadth_first(t):                 # level by level, with a queue
    out, line = [], deque([t] if t is not None else [])
    while line:
        node = line.popleft()
        out.append(node.value)
        for child in (node.left, node.right):
            if child is not None:
                line.append(child)
    return out


if __name__ == "__main__":
    t = Node("A", Node("B", Node("D"), Node("E", Node("G"))),
             Node("C", None, Node("F")))
    for order in [preorder, inorder, postorder, breadth_first]:
        print(f"{order.__name__:13}", " ".join(order(t)))
```

***Listing 25.3.** Four [traversals](#def-g12-trees-traversal); the first three recursive, the last with a queue. code/grade-12/04-trees/listings/traversals.py*

```
$ python traversals.py
preorder      A B D E G C F
inorder       D B G E A C F
postorder     D G E B F C A
breadth_first A B C D E F G
```

***Output 25.2.** The seven [nodes](#def-g12-trees-tree) of the figure, in four orders.*

[Breadth-first order](#def-g12-trees-traversal) cannot be written as “a [node](#def-g12-trees-tree), then its [subtrees](#def-g12-trees-tree)”: the children of B must wait while C is visited. A queue holds the [nodes](#def-g12-trees-tree) found but not yet visited, and gives them back in the order they were found, level after level.

An arithmetic expression is a [tree](#def-g12-trees-tree): each operator is a [node](#def-g12-trees-tree) whose [subtrees](#def-g12-trees-tree) are its operands, and the numbers are the leaves. Its value is computed in [postorder](#def-g12-trees-traversal), operands before operator; [postorder](#def-g12-trees-traversal) writes the [postfix notation](https://one-course.com/books/computer-science/2/en/chapter/24-linked-lists-stacks-and-queues#def-g12-lists-stacks-queues-postfix) of the last chapter, and [inorder](#def-g12-trees-traversal), with brackets, the usual one.

![The expression (3 + 4) × (5 - 2) as a tree, with its four traversals. In postorder each operator comes after its operands; the values computed at each node are written beside it.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-trees/fig-4a4ad75d8a3c.svg)

*The expression $(3 + 4) \times (5 - 2)$ as a [tree](#def-g12-trees-tree), with its four [traversals](#def-g12-trees-traversal). In [postorder](#def-g12-trees-traversal) each operator comes after its operands; the values computed at each [node](#def-g12-trees-tree) are written beside it.*

```python
from node import Node

OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b}


def evaluate(t):                       # postorder: both operands, then the operator
    if t.left is None:
        return t.value                 # a leaf is a number
    return OPS[t.value](evaluate(t.left), evaluate(t.right))


def infix(t):                          # inorder, with brackets around each operation
    if t.left is None:
        return str(t.value)
    return f"({infix(t.left)} {t.value} {infix(t.right)})"


def postfix(t):
    if t.left is None:
        return str(t.value)
    return f"{postfix(t.left)} {postfix(t.right)} {t.value}"


e = Node("*", Node("+", Node(3), Node(4)), Node("-", Node(5), Node(2)))
print(infix(e), "=", evaluate(e))
print("postfix:", postfix(e))
```

***Listing 25.4.** Evaluating and writing an expression [tree](#def-g12-trees-tree). code/grade-12/04-trees/listings/expression_tree.py*

```
$ python expression_tree.py
((3 + 4) * (5 - 2)) = 21
postfix: 3 4 + 5 2 - *
```

***Output 25.3.** The value, and the postfix form read in [postorder](#def-g12-trees-traversal).*

## 25.4 Binary search trees

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

A *binary search tree* is a [binary tree](#def-g12-trees-binary-tree) of keys in which, at every [node](#def-g12-trees-tree), the keys of the left [subtree](#def-g12-trees-tree) are smaller than the [node](#def-g12-trees-tree)’s key and the keys of the right [subtree](#def-g12-trees-tree) are larger.

To find a key, compare it with the [root](#def-g12-trees-tree): equal, found; smaller, go on in the left [subtree](#def-g12-trees-tree); larger, in the right. To insert a key, search for it; where the search falls off the [tree](#def-g12-trees-tree), hang a new [leaf](#def-g12-trees-tree). Both follow one path from the [root](#def-g12-trees-tree), so they visit at most $h + 1$ [nodes](#def-g12-trees-tree) in a [tree](#def-g12-trees-tree) of [height](#def-g12-trees-height) $h$. The functions below loop instead of recursing, for a reason the end of the chapter shows.

```python
"""Binary search trees: smaller keys on the left, larger on the right."""
from node import Node


def insert(t, key):
    """Return the tree t with key added; a key already there is not added again."""
    new = Node(key)
    if t is None:
        return new
    node = t
    while True:                         # a loop, not recursion: trees can be deep
        if key == node.value:
            return t
        side = "left" if key < node.value else "right"
        child = getattr(node, side)
        if child is None:
            setattr(node, side, new)
            return t
        node = child


def search(t, key):
    """Return the number of nodes visited to find key, or None if absent."""
    visited = 0
    while t is not None:
        visited += 1
        if key == t.value:
            return visited
        t = t.left if key < t.value else t.right
    return None


def build(keys):
    t = None
    for k in keys:
        t = insert(t, k)
    return t
```

***Listing 25.5.** Insertion and search in a [binary search tree](#def-g12-trees-bst). code/grade-12/04-trees/listings/bst.py*

The town library’s first ten titles, inserted in the order of its table:

```python
import csv

from bst import build, search
from node import height, size
from traversals import inorder

with open("books.csv", newline="") as f:
    titles = [row["title"] for row in csv.DictReader(f)]

t = build(titles[:10])                       # the first ten, in the table's order
print("root:", t.value, "| size", size(t), "| height", height(t))
print("left of root:", t.left.value, "| right of root:", t.right.value)
for title in ["The Lost Forest", "Seven Code", "The Lost Code"]:
    print(f"{title!r}: visited {search(t, title)}")
for title in inorder(t)[:4]:
    print("  ", title)
print("   ...", len(inorder(t)), "titles in alphabetical order")
```

***Listing 25.6.** A search [tree](#def-g12-trees-tree) of book titles. code/grade-12/04-trees/listings/bst_demo.py*

```
$ python bst_demo.py
root: The Silent Code | size 10 | height 5
left of root: The Paper Forest | right of root: The Silent Kingdom
'The Lost Forest': visited 5
'Seven Code': visited 5
'The Lost Code': visited None
   A Map of the Lighthouse
   A Year by the Bridge
   A Year by the Island
   Seven Code
   ... 10 titles in alphabetical order
```

***Output 25.4.** Titles compare alphabetically; the [inorder](#def-g12-trees-traversal) [traversal](#def-g12-trees-traversal) lists them sorted.*

![The search tree of bst_demo.py. Every title on the left of a node comes before it in alphabetical order, every title on the right after it. The deepest node, shaded, has depth 5: the height of the tree.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-trees/fig-7e3a4ba99e6d.svg)

*The search [tree](#def-g12-trees-tree) of `bst_demo.py`. Every title on the left of a [node](#def-g12-trees-tree) comes before it in alphabetical order, every title on the right after it. The deepest [node](#def-g12-trees-tree), shaded, has [depth](#def-g12-trees-height) $5$: the [height](#def-g12-trees-height) of the [tree](#def-g12-trees-tree).*

**Remark 25.7.**

Alphabetical order here is Python’s order on strings: character by character, by [code point](https://one-course.com/books/computer-science/2/en/chapter/5-text-encodings-from-ascii-to-utf-8#def-g10-text-encodings-code-point). Every capital letter comes before every small one: `"Zoe"` comes before `"apple"`.

## 25.5 Balanced and degenerate trees

**Definition 25.8 (Balanced tree, degenerate tree).**

A [binary tree](#def-g12-trees-binary-tree) is *balanced* when its [height](#def-g12-trees-height) is close to the smallest possible for its [size](#def-g12-trees-height), about the [number of halvings](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-halvings) of $n$. It is *degenerate* when every [node](#def-g12-trees-tree) has at most one [child](#def-g12-trees-tree): it is then a list, of [height](#def-g12-trees-height) $n - 1$.

The shape of a search [tree](#def-g12-trees-tree) depends only on the order of insertion. Keys inserted in increasing order each go to the right of all the others: a [degenerate tree](#def-g12-trees-balanced).

![The same seven keys, two orders of insertion. Finding 7 visits seven nodes on the left, three on the right.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-trees/fig-2ba92a24c9b8.svg)

*The same seven keys, two orders of insertion. Finding $7$ visits seven [nodes](#def-g12-trees-tree) on the left, three on the right.*

```python
import random

from bst import build, search
from node import height

for keys in [[1, 2, 3, 4, 5, 6, 7], [4, 2, 6, 1, 3, 5, 7], [7, 1, 6, 2, 5, 3, 4]]:
    print(keys, "-> height", height(build(keys)))

n = 1023
sorted_tree = build(range(1, n + 1))
shuffled = list(range(1, n + 1))
random.Random(4).shuffle(shuffled)
shuffled_tree = build(shuffled)
print(f"n = {n}, one shuffled order: height {height(shuffled_tree)},"
      f" finding {n} visits {search(shuffled_tree, n)} nodes")
print(f"n = {n}, sorted order: finding {n} visits {search(sorted_tree, n)} nodes")
try:
    height(sorted_tree)
except RecursionError as error:
    print("height of the sorted tree: RecursionError:", error)
```

***Listing 25.7.** [Heights](#def-g12-trees-height) after three orders of seven keys, then $1023$ keys sorted and shuffled. code/grade-12/04-trees/listings/degenerate.py*

```
$ python degenerate.py
[1, 2, 3, 4, 5, 6, 7] -> height 6
[4, 2, 6, 1, 3, 5, 7] -> height 2
[7, 1, 6, 2, 5, 3, 4] -> height 6
n = 1023, one shuffled order: height 20, finding 1023 visits 4 nodes
n = 1023, sorted order: finding 1023 visits 1023 nodes
height of the sorted tree: RecursionError: maximum recursion depth exceeded
```

***Output 25.5.** The sorted [tree](#def-g12-trees-tree) of $1023$ keys is so deep that the recursive `height` fails.*

The recursive `height` calls itself once per level: on a list of $1023$ [nodes](#def-g12-trees-tree), that is beyond Python’s limit of $1000$ frames (chapter [22](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#ch-g12-recursion)). This is why `insert` and `search` loop. [Trees](#def-g12-trees-tree) that keep themselves [balanced](#def-g12-trees-balanced) whatever the order, by reshaping themselves at each insertion, exist: they guarantee a [height](#def-g12-trees-height) in proportion to the [number of halvings](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-halvings) of $n$, and belong to a later volume.

## 25.6 Exercises

**Exercise 25.1 ★.**

Give the [size](#def-g12-trees-height), [height](#def-g12-trees-height) and number of leaves of `Node(1, Node(2, Node(4), Node(5, Node(7), Node(8))), Node(3, Node(6)))`.

**Solution of Exercise 25.1.**

The [root](#def-g12-trees-tree) $1$ has children $2$ and $3$; $2$ has children $4$ and $5$; $5$ has $7$ and $8$; $3$ has $6$. [Size](#def-g12-trees-height) $8$; [height](#def-g12-trees-height) $3$, along $1$, $2$, $5$, $7$; four leaves: $4$, $7$, $8$, $6$.

**Exercise 25.2 ★.**

Give the [preorder](#def-g12-trees-traversal) of the [tree](#def-g12-trees-tree) of exercise [25.1](#exo-g12-trees-1).

**Solution of Exercise 25.2.**

$1, 2, 4, 5, 7, 8, 3, 6$.

**Exercise 25.3 ★.**

Give its [inorder](#def-g12-trees-traversal) and its [postorder](#def-g12-trees-traversal).

**Solution of Exercise 25.3.**

[Inorder](#def-g12-trees-traversal): $4, 2, 7, 5, 8, 1, 6, 3$. [Postorder](#def-g12-trees-traversal): $4, 7, 8, 5, 2, 6, 3, 1$.

**Exercise 25.4 ★.**

Draw the search [tree](#def-g12-trees-tree) obtained by inserting $50$, $30$, $70$, $20$, $40$, $60$, $80$, $35$, in that order. What is its [height](#def-g12-trees-height)?

**Solution of Exercise 25.4.**

$50$ at the [root](#def-g12-trees-tree); $30$ on its left and $70$ on its right; $20$ and $40$ below $30$, $60$ and $80$ below $70$; $35$ is smaller than $50$, larger than $30$, smaller than $40$: the left [child](#def-g12-trees-tree) of $40$. [Height](#def-g12-trees-height) $3$, the [depth](#def-g12-trees-height) of $35$.

**Exercise 25.5 ★.**

Write `count_at_depth(t, d)`, the number of [nodes](#def-g12-trees-tree) of [depth](#def-g12-trees-height) `d` in the [tree](#def-g12-trees-tree) `t`.

**Solution of Exercise 25.5.**

    `def count_at_depth(t, d):`

        `if t is None:`

            `return 0`

        `if d == 0:`

            `return 1`

        `return count_at_depth(t.left, d - 1) + count_at_depth(t.right, d - 1)`

A [node](#def-g12-trees-tree) at [depth](#def-g12-trees-height) $d$ in `t` is at [depth](#def-g12-trees-height) $d - 1$ in one of its [subtrees](#def-g12-trees-tree). On the [tree](#def-g12-trees-tree) of exercise [25.4](#exo-g12-trees-4): $1, 2, 4, 1$ for [depths](#def-g12-trees-height) $0$ to $3$.

**Exercise 25.6 ★★.**

A student writes `height` with `return 0` for the empty [tree](#def-g12-trees-tree). What does it return for a single [node](#def-g12-trees-tree), and for the [tree](#def-g12-trees-tree) of the first figure? How must the bounds of the theorem be rewritten for that function?

**Solution of Exercise 25.6.**

It returns $1$ for a single [node](#def-g12-trees-tree) and $4$ for the [tree](#def-g12-trees-tree) of the first figure: it counts the [nodes](#def-g12-trees-tree) on the longest path, not the links, so it gives $h + 1$. Both conventions are in use; a text must state its own. For this function $h' = h + 1$, the bounds read $h' \le n \le 2^{h'} - 1$.

**Exercise 25.7 ★★.**

Write `bst_min(t)`, the smallest key of a non-empty search [tree](#def-g12-trees-tree), without visiting more than one path.

**Solution of Exercise 25.7.**

    `def bst_min(t):`

        `while t.left is not None:`

            `t = t.left`

        `return t.value`

Every key smaller than a [node](#def-g12-trees-tree)’s is in its left [subtree](#def-g12-trees-tree): when there is none, the [node](#def-g12-trees-tree) holds the smallest key. The path followed is the leftmost one.

**Exercise 25.8 ★★.**

What is the smallest possible [height](#def-g12-trees-height) of a [binary tree](#def-g12-trees-binary-tree) of $100$ [nodes](#def-g12-trees-tree)?

**Solution of Exercise 25.8.**

A [tree](#def-g12-trees-tree) of [height](#def-g12-trees-height) $h$ holds at most $2^{h+1} - 1$ [nodes](#def-g12-trees-tree). $2^6 - 1 = 63 < 100$ but $2^7 - 1 = 127 \ge 100$: the [height](#def-g12-trees-height) is at least $6$, and $6$ is reached by filling [depths](#def-g12-trees-height) $0$ to $5$ ($63$ [nodes](#def-g12-trees-tree)) and placing $37$ [nodes](#def-g12-trees-tree) at [depth](#def-g12-trees-height) $6$.

**Exercise 25.9 ★★.**

Give the [breadth-first order](#def-g12-trees-traversal) of the [tree](#def-g12-trees-tree) of exercise [25.4](#exo-g12-trees-4).

**Solution of Exercise 25.9.**

$50, 30, 70, 20, 40, 60, 80, 35$.

**Exercise 25.10 ★★.**

This recursive insertion is called as `t = insert(t, k)`. Inserting $50$, $30$, $70$ leaves a [tree](#def-g12-trees-tree) of one [node](#def-g12-trees-tree). Why? Correct it.

    `def insert(t, key):`

        `if t is None:`

            `return Node(key)`

        `if key < t.value:`

            `insert(t.left, key)`

        `else:`

            `insert(t.right, key)`

        `return t`

**Solution of Exercise 25.10.**

The recursive call returns the [subtree](#def-g12-trees-tree) with the key added, and the caller throws it away. When the call reaches an empty [subtree](#def-g12-trees-tree), it makes the new [node](#def-g12-trees-tree) and returns it, but nothing links it to its [parent](#def-g12-trees-tree). The repair stores the result:

    `if key < t.value:`

        `t.left = insert(t.left, key)`

    `elif key > t.value:`

        `t.right = insert(t.right, key)`

The `elif` also leaves a key already present out, as `bst.py` does.

**Exercise 25.11 ★★.**

Write `is_bst(t)`. Show that checking, at each [node](#def-g12-trees-tree), only that the left [child](#def-g12-trees-tree) is smaller and the right [child](#def-g12-trees-tree) larger is not enough.

**Solution of Exercise 25.11.**

    `def is_bst(t, low=None, high=None):`

        `if t is None:`

            `return True`

        `if low is not None and t.value <= low:`

            `return False`

        `if high is not None and t.value >= high:`

            `return False`

        `return is_bst(t.left, low, t.value) and is_bst(t.right, t.value, high)`

Each key must lie strictly between `low` and `high`, the bounds set by all its ancestors. Checking only the children accepts `Node(5, Node(3, None, Node(6)), Node(8))`: $6$ is larger than its [parent](#def-g12-trees-tree) $3$, as a right [child](#def-g12-trees-tree) should be, but it lies in the left [subtree](#def-g12-trees-tree) of $5$ and is larger than $5$. A search for $6$ would go right at the [root](#def-g12-trees-tree) and miss it.

**Exercise 25.12 ★★★.**

Prove, by induction on the recursive definition, that a [binary tree](#def-g12-trees-binary-tree) of [height](#def-g12-trees-height) $h$ and [size](#def-g12-trees-height) $n$ satisfies $n \le 2^{h+1} - 1$.

**Solution of Exercise 25.12.**

Let $P(t)$: “$t$ has [size](#def-g12-trees-height) $n \le 2^{h+1} - 1$, $h$ its [height](#def-g12-trees-height)”. For the empty [tree](#def-g12-trees-tree), $h = -1$ and $n = 0 = 2^0 - 1$. For a [node](#def-g12-trees-tree) with [subtrees](#def-g12-trees-tree) $L$ and $R$, assume $P(L)$ and $P(R)$. Their [heights](#def-g12-trees-height) are at most $h - 1$, so their [sizes](#def-g12-trees-height) are at most $2^h - 1$ each, and $n = 1 + n_L + n_R \le 1 + 2(2^h - 1) = 2^{h+1} - 1$. Every [binary tree](#def-g12-trees-binary-tree) is built from the empty [tree](#def-g12-trees-tree) by forming [nodes](#def-g12-trees-tree), so $P$ holds for all.

**Exercise 25.13 ★★★.**

Prove that the [inorder](#def-g12-trees-traversal) [traversal](#def-g12-trees-traversal) of a [binary search tree](#def-g12-trees-bst) lists its keys in increasing order.

**Solution of Exercise 25.13.**

By induction on the [size](#def-g12-trees-height). The empty [tree](#def-g12-trees-tree) gives the empty list, which is sorted. For a [node](#def-g12-trees-tree) of key $k$, both [subtrees](#def-g12-trees-tree) are search [trees](#def-g12-trees-tree), since the property holds at each of their [nodes](#def-g12-trees-tree); by induction their [inorders](#def-g12-trees-traversal) are sorted. Every key of the left list is smaller than $k$, every key of the right list larger. The [inorder](#def-g12-trees-traversal) is the left list, then $k$, then the right list: sorted.

**Exercise 25.14 ★★★.**

A [tree](#def-g12-trees-tree) has distinct values. Write `rebuild(pre, ino)`, which rebuilds it from its [preorder](#def-g12-trees-traversal) and its [inorder](#def-g12-trees-traversal).

**Solution of Exercise 25.14.**

    `def rebuild(pre, ino):`

        `if not pre:`

            `return None`

        `root = pre[0]`

        `k = ino.index(root)`

        `left = rebuild(pre[1:k + 1], ino[:k])`

        `return Node(root, left, rebuild(pre[k + 1:], ino[k + 1:]))`

The [preorder](#def-g12-trees-traversal) starts with the [root](#def-g12-trees-tree). In the [inorder](#def-g12-trees-traversal), the [root](#def-g12-trees-tree) separates the left [subtree](#def-g12-trees-tree)’s values, $k$ of them, from the right’s. In the [preorder](#def-g12-trees-traversal), the [root](#def-g12-trees-tree) is followed by the $k$ values of the left [subtree](#def-g12-trees-tree), then the right’s. Each pair of lists is the [preorder](#def-g12-trees-traversal) and [inorder](#def-g12-trees-traversal) of a smaller [tree](#def-g12-trees-tree). The values must be distinct, or `index` could find the wrong [node](#def-g12-trees-tree).

**Exercise 25.15 ★★★.**

How many [binary trees](#def-g12-trees-binary-tree) of [size](#def-g12-trees-height) $3$ are there, counting shapes only? Of [size](#def-g12-trees-height) $4$? Write a [recursive function](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#def-g12-recursion-recursion) that counts those of [size](#def-g12-trees-height) $n$.

**Solution of Exercise 25.15.**

[Size](#def-g12-trees-height) $3$: five shapes (a chain going left–left, left–right, right–left or right–right, and the [root](#def-g12-trees-tree) with two children). [Size](#def-g12-trees-height) $4$: fourteen. A [tree](#def-g12-trees-tree) of [size](#def-g12-trees-height) $n \ge 1$ is a [root](#def-g12-trees-tree) with a left [subtree](#def-g12-trees-tree) of some [size](#def-g12-trees-height) $k$, from $0$ to $n - 1$, and a right [subtree](#def-g12-trees-tree) of [size](#def-g12-trees-height) $n - 1 - k$; the two choices are independent:

    `def count_shapes(n):`

        `if n == 0:`

            `return 1`

        `return sum(count_shapes(k) * count_shapes(n - 1 - k) for k in range(n))`

It gives $1, 1, 2, 5, 14, 42$ for $n = 0$ to $5$; for $4$, $5 + 2 + 2 + 5 = 14$.

## 25.7 Problem: How Tall Is a Search Tree?

**Problem 25.1.**

Weekend problem — the height of a search tree

The keys $1, 2, \dots, 1023$ are inserted into a search [tree](#def-g12-trees-tree), in an order that decides its [height](#def-g12-trees-height). The program below builds $1000$ [trees](#def-g12-trees-tree) from $1000$ random orders of the same keys, and counts the [heights](#def-g12-trees-height); the chart draws the counts.

```python
"""The heights of search trees built from 1000 random orders of 1..1023."""
import random
from collections import Counter

from bst import build
from node import height


def heights(n=1023, trials=1000, seed=2026):
    rng = random.Random(seed)
    keys = list(range(1, n + 1))
    out = []
    for _ in range(trials):
        rng.shuffle(keys)
        out.append(height(build(keys)))
    return out


if __name__ == "__main__":
    h = heights()
    print("smallest", min(h), "| largest", max(h), "| mean", round(sum(h) / len(h), 2))
    counts = Counter(h)
    print(" ".join(f"{k}:{counts[k]}" for k in sorted(counts)))
```

***Listing 25.8.** [Heights](#def-g12-trees-height) of $1000$ random search [trees](#def-g12-trees-tree). code/grade-12/04-trees/listings/random_heights.py*

```
$ python random_heights.py
smallest 16 | largest 31 | mean 21.13
16:1 17:8 18:49 19:149 20:211 21:192 22:153 23:133 24:57 25:23 26:15 27:3 28:2 29:3 31:1
```

***Output 25.6.** The smallest, largest and mean [heights](#def-g12-trees-height), then how many [trees](#def-g12-trees-tree) had each [height](#def-g12-trees-height).*

![Heights of the 1000 search trees of 1023 keys, from figures/heights_hist.py. None comes near the worst case of 1022; none reaches the best case of 9 either.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-trees/fig-0c08dbb93afc.svg)

*[Heights](#def-g12-trees-height) of the $1000$ search [trees](#def-g12-trees-tree) of $1023$ keys, from `figures/heights_hist.py`. None comes near the worst case of $1022$; none reaches the best case of $9$ either.*

**Part I — A search tree of $n$ keys.**

1. Why does finding a key in a search [tree](#def-g12-trees-tree) of [height](#def-g12-trees-height) $h$ visit at most $h + 1$ [nodes](#def-g12-trees-tree) ?
2. Does the same hold for a key that is absent?
3. Why is the [inorder](#def-g12-trees-traversal) [traversal](#def-g12-trees-traversal) of every one of the $1000$ [trees](#def-g12-trees-tree) the same?
4. Which key is at the [root](#def-g12-trees-tree) of each [tree](#def-g12-trees-tree) ?

**Part II — The worst case.**

5. Show that inserting $1, 2, \dots, n$ in increasing order gives a [tree](#def-g12-trees-tree) of [height](#def-g12-trees-height) $n - 1$ .
6. Give another order of $1, \dots, 7$ that gives [height](#def-g12-trees-height) $6$ , other than increasing and decreasing.
7. Why does the recursive `height` fail on the sorted [tree](#def-g12-trees-tree) of $1023$ keys, while `search` works?
8. How many [nodes](#def-g12-trees-tree) does finding $1023$ visit in the sorted [tree](#def-g12-trees-tree) , and why?

**Part III — The best case.**

9. From the theorem, what is the smallest [height](#def-g12-trees-height) of a [tree](#def-g12-trees-tree) of $1023$ [nodes](#def-g12-trees-tree) ?
10. Describe an order of insertion of $1, \dots, 1023$ that reaches it.
11. In that [tree](#def-g12-trees-tree) , how many [nodes](#def-g12-trees-tree) does any search visit at most?
12. Write that order for $1, \dots, 7$ , and check it against the output of `degenerate.py` .

**Part IV — Random orders.**

13. Read the smallest, largest and mean [heights](#def-g12-trees-height) of the $1000$ random [trees](#def-g12-trees-tree) .
14. Which [height](#def-g12-trees-height) is the most frequent? How many [trees](#def-g12-trees-tree) out of $1000$ had a [height](#def-g12-trees-height) of $25$ or more?
15. Compare the mean with the best [height](#def-g12-trees-height) $9$ and the worst $1022$ : how many times larger than the best, and how many times smaller than the worst?
16. Why is a [height](#def-g12-trees-height) of $1022$ possible, but never seen?
17. Searching a random [tree](#def-g12-trees-tree) visits at most how many [nodes](#def-g12-trees-tree) , in the tallest of the $1000$ ?
18. Why is the experiment built from a fixed seed?
19. The library inserts its titles in the order of its table. Is that order random with respect to the titles? What would happen if the table were sorted by title?
20. State the result: the best [height](#def-g12-trees-height) , the worst [height](#def-g12-trees-height) , and the measured [heights](#def-g12-trees-height) .

**Solution of Problem 25.1.**

**1.** Each comparison moves one level down, along one path from the [root](#def-g12-trees-tree); a path in a [tree](#def-g12-trees-tree) of [height](#def-g12-trees-height) $h$ has at most $h + 1$ [nodes](#def-g12-trees-tree).

**2.** Yes: the search for an absent key also follows one path, until it falls off below a [node](#def-g12-trees-tree).

**3.** The [inorder](#def-g12-trees-traversal) of a search [tree](#def-g12-trees-tree) is its keys in increasing order (exercise [25.13](#exo-g12-trees-13)): it is $1, 2, \dots, 1023$ for every [tree](#def-g12-trees-tree), whatever its shape.

**4.** The first key of the order: a key, once inserted, never moves, and the first one becomes the [root](#def-g12-trees-tree).

**5.** Each new key is larger than all the keys already in the [tree](#def-g12-trees-tree): compared with each [node](#def-g12-trees-tree) on its way, it goes right every time, and hangs as the right [child](#def-g12-trees-tree) of the previous key. The [tree](#def-g12-trees-tree) is one chain of $n$ [nodes](#def-g12-trees-tree), of [height](#def-g12-trees-height) $n - 1$.

**6.** For instance $1, 7, 2, 6, 3, 5, 4$: each key is the smallest or the largest of those not yet inserted, so it hangs below the previous one. ($7, 1, 6, 2, 5, 3, 4$ is the one in the output.)

**7.** The recursive `height` calls itself once per level, $1024$ calls deep including the empty [tree](#def-g12-trees-tree), more than the $1000$ frames allowed. `search` is a loop: a deep [tree](#def-g12-trees-tree) costs it time, not stack.

**8.** $1023$: the key $1023$ is at the end of the chain, and every [node](#def-g12-trees-tree) lies on the path to it.

**9.** $1023 = 2^{10} - 1$ [nodes](#def-g12-trees-tree) need $2^{h+1} - 1 \ge 1023$, so $h \ge 9$; [height](#def-g12-trees-height) $9$ is reached by a [tree](#def-g12-trees-tree) with every [depth](#def-g12-trees-height) from $0$ to $9$ full.

**10.** The middle key first, $512$; then the middles of the two halves, $256$ and $768$; then the middles of the four quarters, $128$, $384$, $640$, $896$; and so on, level by level. Each key comes after the keys above it in the full [tree](#def-g12-trees-tree), so it lands at its place.

**11.** $10$, on any path of the full [tree](#def-g12-trees-tree).

**12.** $4, 2, 6, 1, 3, 5, 7$: [height](#def-g12-trees-height) $2$ in the output, the smallest for $7 = 2^3 - 1$ [nodes](#def-g12-trees-tree).

**13.** Smallest $16$, largest $31$, mean $21.13$.

**14.** $20$, for $211$ [trees](#def-g12-trees-tree). A [height](#def-g12-trees-height) of $25$ or more: $23 + 15 + 3 + 2 + 3 + 1 = 47$ [trees](#def-g12-trees-tree) out of $1000$.

**15.** $21.13 / 9 \approx 2.3$ times the best; $1022 / 21.13 \approx 48$ times smaller than the worst.

**16.** The chains are the orders where each key is the smallest or the largest of those left: two choices for each of the first $1022$ keys, so $2^{1022}$ orders, about $10^{308}$. There are $1023!$ orders in all, about $10^{2637}$. A thousand random orders have no chance worth counting of meeting a chain.

**17.** $32$, in the [tree](#def-g12-trees-tree) of [height](#def-g12-trees-height) $31$; against $1023$ in the sorted [tree](#def-g12-trees-tree).

**18.** So that the run gives the same $1000$ orders each time: the printed output and the chart agree with each other and with any rerun.

**19.** The table’s order has nothing to do with alphabetical order, so it behaves like a random one: ten titles gave [height](#def-g12-trees-height) $5$. Sorted by title, the table would give a chain: [height](#def-g12-trees-height) $79$ for its $80$ titles, and $80$ [nodes](#def-g12-trees-tree) visited for the last.

**20.** **For $1023$ keys, the best [height](#def-g12-trees-height) is $9$ and the worst $1022$; over $1000$ random orders the measured [heights](#def-g12-trees-height) ran from $16$ to $31$, with a mean of $21.13$.**
