Informática · Libro 2 · Cursos 10–12

High School Computer Science

Este libro aún no está disponible en Español. Ediciones: English.

High School Computer Science · Cursos 10–12

25Trees and Binary Search Trees

“I am thinking of a number between 11 and 100100.” The best first guess is 5050; after “smaller”, 2525; after “larger”, 3737. Every game follows one path through a fixed set of questions: 5050 at the top, 2525 and 7575 below it, then 1212, 3737, 6262, 8787, and so on. Drawn out, these questions form a 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, builds binary trees with a class, visits their nodes in four orders, and stores keys in binary search trees, where finding a key costs as many steps as the tree is tall. Then it asks how tall such a tree grows, and measures it.

You already know

A recursive function calls itself on smaller inputs, and is proved by induction (chapter 22). A queue gives back its elements in the order they came (chapter 24). Folders inside folders (Book 1, grade 3) and the nested elements of a web page (Book 1, grade 9) are trees.

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 is the number of links from the root to it: the root has depth 00. The height of a tree is the largest depth of its nodes; a tree of one node has height 00, and by convention the empty tree has height −1-1. The size of a tree is its number of nodes.

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.
A tree of size 77 and height 33. 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 44, height 22.

25.2 Binary trees

Definition 25.3 (Binary tree)

A binary tree is either empty, or a node holding a value and two binary trees, its left subtree and its right subtree.

The definition is recursive, and so are the functions on binary trees: each one says what to do with the empty tree, and how to combine the answers of the two subtrees. In Python the empty tree is None.

"""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: a class of nodes, and three recursive measures. code/grade-12/04-trees/listings/node.py
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 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.

Theorem 25.4 (Size and height)

A binary tree of height h≥0h \ge 0 has a size nn with h+1≤n≤2h+1−1h + 1 \le n \le 2^{h+1} - 1.

The lower bound holds because a path from the root to the deepest node already holds h+1h + 1 nodes. For the upper bound, depth dd holds at most 2d2^d nodes, since each node has at most two children, and 1+2+4+⋯+2h=2h+1−11 + 2 + 4 + \dots + 2^h = 2^{h+1} - 1. Exercise 25.12 proves it again, by induction on the recursive definition. Turned around: a binary tree of nn nodes has a height of at least the number of times n+1n + 1 can be halved, minus one; 10231023 nodes need a height of at least 99.

25.3 Traversals

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

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

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; 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 of the figure, in four orders.

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

An arithmetic expression is a tree: each operator is a node whose subtrees are its operands, and the numbers are the leaves. Its value is computed in postorder, operands before operator; postorder writes the postfix notation of the last chapter, and inorder, 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.
The expression (3+4)×(5−2)(3 + 4) \times (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.
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. 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.

25.4 Binary search trees

Definition 25.6 (Binary search tree)

A binary search tree is a binary tree of keys in which, 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.

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

"""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. code/grade-12/04-trees/listings/bst.py

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

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 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 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.
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 55: the height of the tree.

Remark 25.7

Alphabetical order here is Python’s order on strings: character by character, by 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 is balanced when its height is close to the smallest possible for its size, about the number of halvings of nn. It is degenerate when every node has at most one child: it is then a list, of height n−1n - 1.

The shape of a search 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.

The same seven keys, two orders of insertion. Finding 7 visits seven nodes on the left, three on the right.
The same seven keys, two orders of insertion. Finding 77 visits seven nodes on the left, three on the right.
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 after three orders of seven keys, then 10231023 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 of 10231023 keys is so deep that the recursive height fails.

The recursive height calls itself once per level: on a list of 10231023 nodes, that is beyond Python’s limit of 10001000 frames (chapter 22). This is why insert and search loop. Trees that keep themselves balanced whatever the order, by reshaping themselves at each insertion, exist: they guarantee a height in proportion to the number of halvings of nn, and belong to a later volume.

25.6 Exercises

Exercise 25.1 ★

Give the size, height and number of leaves of Node(1, Node(2, Node(4), Node(5, Node(7), Node(8))), Node(3, Node(6))).

Solution

Solution of Exercise 25.1.

The root 11 has children 22 and 33; 22 has children 44 and 55; 55 has 77 and 88; 33 has 66. Size 88; height 33, along 11, 22, 55, 77; four leaves: 44, 77, 88, 66.

Exercise 25.2 ★

Give the preorder of the tree of exercise 25.1.

Solution

Solution of Exercise 25.2.

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

Exercise 25.3 ★

Give its inorder and its postorder.

Solution

Solution of Exercise 25.3.

Inorder: 4,2,7,5,8,1,6,34, 2, 7, 5, 8, 1, 6, 3. Postorder: 4,7,8,5,2,6,3,14, 7, 8, 5, 2, 6, 3, 1.

Exercise 25.4 ★

Draw the search tree obtained by inserting 5050, 3030, 7070, 2020, 4040, 6060, 8080, 3535, in that order. What is its height?

Solution

Solution of Exercise 25.4.

5050 at the root; 3030 on its left and 7070 on its right; 2020 and 4040 below 3030, 6060 and 8080 below 7070; 3535 is smaller than 5050, larger than 3030, smaller than 4040: the left child of 4040. Height 33, the depth of 3535.

Exercise 25.5 ★

Write count_at_depth(t, d), the number of nodes of depth d in the tree t.

Solution

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 at depth dd in t is at depth d−1d - 1 in one of its subtrees. On the tree of exercise 25.4: 1,2,4,11, 2, 4, 1 for depths 00 to 33.

Exercise 25.6 ★★

A student writes height with return 0 for the empty tree. What does it return for a single node, and for the tree of the first figure? How must the bounds of the theorem be rewritten for that function?

Solution

Solution of Exercise 25.6.

It returns 11 for a single node and 44 for the tree of the first figure: it counts the nodes on the longest path, not the links, so it gives h+1h + 1. Both conventions are in use; a text must state its own. For this function h′=h+1h' = h + 1, the bounds read h′≤n≤2h′−1h' \le n \le 2^{h'} - 1.

Exercise 25.7 ★★

Write bst_min(t), the smallest key of a non-empty search tree, without visiting more than one path.

Solution

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’s is in its left subtree: when there is none, the node holds the smallest key. The path followed is the leftmost one.

Exercise 25.8 ★★

What is the smallest possible height of a binary tree of 100100 nodes?

Solution

Solution of Exercise 25.8.

A tree of height hh holds at most 2h+1−12^{h+1} - 1 nodes. 26−1=63<1002^6 - 1 = 63 < 100 but 27−1=127≥1002^7 - 1 = 127 \ge 100: the height is at least 66, and 66 is reached by filling depths 00 to 55 (6363 nodes) and placing 3737 nodes at depth 66.

Exercise 25.9 ★★

Give the breadth-first order of the tree of exercise 25.4.

Solution

Solution of Exercise 25.9.

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

Exercise 25.10 ★★

This recursive insertion is called as t = insert(t, k). Inserting 5050, 3030, 7070 leaves a tree of one node. 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

Solution of Exercise 25.10.

The recursive call returns the subtree with the key added, and the caller throws it away. When the call reaches an empty subtree, it makes the new node and returns it, but nothing links it to its parent. 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, only that the left child is smaller and the right child larger is not enough.

Solution

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)): 66 is larger than its parent 33, as a right child should be, but it lies in the left subtree of 55 and is larger than 55. A search for 66 would go right at the root and miss it.

Exercise 25.12 ★★★

Prove, by induction on the recursive definition, that a binary tree of height hh and size nn satisfies n≤2h+1−1n \le 2^{h+1} - 1.

Solution

Solution of Exercise 25.12.

Let P(t)P(t): “tt has size n≤2h+1−1n \le 2^{h+1} - 1, hh its height”. For the empty tree, h=−1h = -1 and n=0=20−1n = 0 = 2^0 - 1. For a node with subtrees LL and RR, assume P(L)P(L) and P(R)P(R). Their heights are at most h−1h - 1, so their sizes are at most 2h−12^h - 1 each, and n=1+nL+nR≤1+2(2h−1)=2h+1−1n = 1 + n_L + n_R \le 1 + 2(2^h - 1) = 2^{h+1} - 1. Every binary tree is built from the empty tree by forming nodes, so PP holds for all.

Exercise 25.13 ★★★

Prove that the inorder traversal of a binary search tree lists its keys in increasing order.

Solution

Solution of Exercise 25.13.

By induction on the size. The empty tree gives the empty list, which is sorted. For a node of key kk, both subtrees are search trees, since the property holds at each of their nodes; by induction their inorders are sorted. Every key of the left list is smaller than kk, every key of the right list larger. The inorder is the left list, then kk, then the right list: sorted.

Exercise 25.14 ★★★

A tree has distinct values. Write rebuild(pre, ino), which rebuilds it from its preorder and its inorder.

Solution

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 starts with the root. In the inorder, the root separates the left subtree’s values, kk of them, from the right’s. In the preorder, the root is followed by the kk values of the left subtree, then the right’s. Each pair of lists is the preorder and inorder of a smaller tree. The values must be distinct, or index could find the wrong node.

Exercise 25.15 ★★★

How many binary trees of size 33 are there, counting shapes only? Of size 44? Write a recursive function that counts those of size nn.

Solution

Solution of Exercise 25.15.

Size 33: five shapes (a chain going left–left, left–right, right–left or right–right, and the root with two children). Size 44: fourteen. A tree of size n≥1n \ge 1 is a root with a left subtree of some size kk, from 00 to n−1n - 1, and a right subtree of size n−1−kn - 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,421, 1, 2, 5, 14, 42 for n=0n = 0 to 55; for 44, 5+2+2+5=145 + 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,…,10231, 2, \dots, 1023 are inserted into a search tree, in an order that decides its height. The program below builds 10001000 trees from 10001000 random orders of the same keys, and counts the heights; the chart draws the counts.

"""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 of 10001000 random search trees. 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, then how many trees had each 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.
Heights of the 10001000 search trees of 10231023 keys, from figures/heights_hist.py. None comes near the worst case of 10221022; none reaches the best case of 99 either.

Part I — A search tree of nn keys.

  1. Why does finding a key in a search tree of height hh visit at most h+1h + 1 nodes?
  2. Does the same hold for a key that is absent?
  3. Why is the inorder traversal of every one of the 10001000 trees the same?
  4. Which key is at the root of each tree?

Part II — The worst case.

  1. Show that inserting 1,2,…,n1, 2, \dots, n in increasing order gives a tree of height n−1n - 1.
  2. Give another order of 1,…,71, \dots, 7 that gives height 66, other than increasing and decreasing.
  3. Why does the recursive height fail on the sorted tree of 10231023 keys, while search works?
  4. How many nodes does finding 10231023 visit in the sorted tree, and why?

Part III — The best case.

  1. From the theorem, what is the smallest height of a tree of 10231023 nodes?
  2. Describe an order of insertion of 1,…,10231, \dots, 1023 that reaches it.
  3. In that tree, how many nodes does any search visit at most?
  4. Write that order for 1,…,71, \dots, 7, and check it against the output of degenerate.py.

Part IV — Random orders.

  1. Read the smallest, largest and mean heights of the 10001000 random trees.
  2. Which height is the most frequent? How many trees out of 10001000 had a height of 2525 or more?
  3. Compare the mean with the best height 99 and the worst 10221022: how many times larger than the best, and how many times smaller than the worst?
  4. Why is a height of 10221022 possible, but never seen?
  5. Searching a random tree visits at most how many nodes, in the tallest of the 10001000?
  6. Why is the experiment built from a fixed seed?
  7. 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?
  8. State the result: the best height, the worst height, and the measured heights.
Solution

Solution of Problem 25.1.

1. Each comparison moves one level down, along one path from the root; a path in a tree of height hh has at most h+1h + 1 nodes.

2. Yes: the search for an absent key also follows one path, until it falls off below a node.

3. The inorder of a search tree is its keys in increasing order (exercise 25.13): it is 1,2,…,10231, 2, \dots, 1023 for every tree, whatever its shape.

4. The first key of the order: a key, once inserted, never moves, and the first one becomes the root.

5. Each new key is larger than all the keys already in the tree: compared with each node on its way, it goes right every time, and hangs as the right child of the previous key. The tree is one chain of nn nodes, of height n−1n - 1.

6. For instance 1,7,2,6,3,5,41, 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,47, 1, 6, 2, 5, 3, 4 is the one in the output.)

7. The recursive height calls itself once per level, 10241024 calls deep including the empty tree, more than the 10001000 frames allowed. search is a loop: a deep tree costs it time, not stack.

8. 10231023: the key 10231023 is at the end of the chain, and every node lies on the path to it.

9. 1023=210−11023 = 2^{10} - 1 nodes need 2h+1−1≥10232^{h+1} - 1 \ge 1023, so h≥9h \ge 9; height 99 is reached by a tree with every depth from 00 to 99 full.

10. The middle key first, 512512; then the middles of the two halves, 256256 and 768768; then the middles of the four quarters, 128128, 384384, 640640, 896896; and so on, level by level. Each key comes after the keys above it in the full tree, so it lands at its place.

11. 1010, on any path of the full tree.

12. 4,2,6,1,3,5,74, 2, 6, 1, 3, 5, 7: height 22 in the output, the smallest for 7=23−17 = 2^3 - 1 nodes.

13. Smallest 1616, largest 3131, mean 21.1321.13.

14. 2020, for 211211 trees. A height of 2525 or more: 23+15+3+2+3+1=4723 + 15 + 3 + 2 + 3 + 1 = 47 trees out of 10001000.

15. 21.13/9≈2.321.13 / 9 \approx 2.3 times the best; 1022/21.13≈481022 / 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 10221022 keys, so 210222^{1022} orders, about 1030810^{308}. There are 1023!1023! orders in all, about 10263710^{2637}. A thousand random orders have no chance worth counting of meeting a chain.

17. 3232, in the tree of height 3131; against 10231023 in the sorted tree.

18. So that the run gives the same 10001000 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 55. Sorted by title, the table would give a chain: height 7979 for its 8080 titles, and 8080 nodes visited for the last.

20. For 10231023 keys, the best height is 99 and the worst 10221022; over 10001000 random orders the measured heights ran from 1616 to 3131, with a mean of 21.1321.13.

Términos definidos en este capítulo

Ver los 1050 términos del glosario