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 and .” The best first guess is ; after “smaller”, ; after “larger”, . Every game follows one path through a fixed set of questions: at the top, and below it, then , , , , 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 . The height of a tree is the largest depth of its nodes; a tree of one node has height , and by convention the empty tree has height . The size of a tree is its number of nodes.
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)
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))
$ python size_height.py
size 7 | height 3 | leaves 3
subtree B: size 4 | height 2
single node: height 0 | empty tree: height -1
Theorem 25.4 (Size and height)
A binary tree of height has a size with .
The lower bound holds because a path from the root to the deepest node already holds nodes. For the upper bound, depth holds at most nodes, since each node has at most two children, and . Exercise 25.12 proves it again, by induction on the recursive definition. Turned around: a binary tree of nodes has a height of at least the number of times can be halved, minus one; nodes need a height of at least .
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)))
$ 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
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.
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))
$ python expression_tree.py
((3 + 4) * (5 - 2)) = 21
postfix: 3 4 + 5 2 - *
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 nodes in a tree of height . 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
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")
$ 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
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 : 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 . It is degenerate when every node has at most one child: it is then a list, of height .
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.
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)
$ 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
height fails.The recursive height calls itself once per level: on a list of nodes, that is beyond Python’s limit of 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 , 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))).
Exercise 25.2 ★
Give the preorder of the tree of exercise 25.1.
Solution
Solution of Exercise 25.2.
.
Exercise 25.3 ★
Exercise 25.4 ★
Draw the search tree obtained by inserting , , , , , , , , in that order. What is its height?
Exercise 25.5 ★
Write count_at_depth(t, d), the number of nodes of depth d in the tree t.
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?
Exercise 25.7 ★★
Write bst_min(t), the smallest key of a non-empty search tree, without visiting more than one path.
Exercise 25.8 ★★
What is the smallest possible height of a binary tree of nodes?
Exercise 25.9 ★★
Give the breadth-first order of the tree of exercise 25.4.
Solution
Solution of Exercise 25.9.
.
Exercise 25.10 ★★
This recursive insertion is called as t = insert(t, k). Inserting , , 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)): is larger than its parent , as a right child should be, but it lies in the left subtree of and is larger than . A search for 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 and size satisfies .
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 , 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 , every key of the right list larger. The inorder is the left list, then , 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, of them, from the right’s. In the preorder, the root is followed by the 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 are there, counting shapes only? Of size ? Write a recursive function that counts those of size .
Solution
Solution of Exercise 25.15.
Size : five shapes (a chain going left–left, left–right, right–left or right–right, and the root with two children). Size : fourteen. A tree of size is a root with a left subtree of some size , from to , and a right subtree of size ; 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 for to ; for , .
25.7 Problem: How Tall Is a Search Tree?
Problem 25.1
Weekend problem — the height of a search tree
The keys are inserted into a search tree, in an order that decides its height. The program below builds trees from 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)))
$ 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
figures/heights_hist.py. None comes near the worst case of ; none reaches the best case of either.Part I — A search tree of keys.
- Why does finding a key in a search tree of height visit at most nodes?
- Does the same hold for a key that is absent?
- Why is the inorder traversal of every one of the trees the same?
- Which key is at the root of each tree?
Part II — The worst case.
- Show that inserting in increasing order gives a tree of height .
- Give another order of that gives height , other than increasing and decreasing.
- Why does the recursive
heightfail on the sorted tree of keys, whilesearchworks? - How many nodes does finding visit in the sorted tree, and why?
Part III — The best case.
- From the theorem, what is the smallest height of a tree of nodes?
- Describe an order of insertion of that reaches it.
- In that tree, how many nodes does any search visit at most?
- Write that order for , and check it against the output of
degenerate.py.
Part IV — Random orders.
- Read the smallest, largest and mean heights of the random trees.
- Which height is the most frequent? How many trees out of had a height of or more?
- Compare the mean with the best height and the worst : how many times larger than the best, and how many times smaller than the worst?
- Why is a height of possible, but never seen?
- Searching a random tree visits at most how many nodes, in the tallest of the ?
- Why is the experiment built from a fixed seed?
- 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?
- 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 has at most 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 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 nodes, of height .
6. For instance : each key is the smallest or the largest of those not yet inserted, so it hangs below the previous one. ( is the one in the output.)
7. The recursive height calls itself once per level, calls deep including the empty tree, more than the frames allowed. search is a loop: a deep tree costs it time, not stack.
8. : the key is at the end of the chain, and every node lies on the path to it.
9. nodes need , so ; height is reached by a tree with every depth from to full.
10. The middle key first, ; then the middles of the two halves, and ; then the middles of the four quarters, , , , ; 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. , on any path of the full tree.
12. : height in the output, the smallest for nodes.
13. Smallest , largest , mean .
14. , for trees. A height of or more: trees out of .
15. times the best; 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 keys, so orders, about . There are orders in all, about . A thousand random orders have no chance worth counting of meeting a chain.
17. , in the tree of height ; against in the sorted tree.
18. So that the run gives the same 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 . Sorted by title, the table would give a chain: height for its titles, and nodes visited for the last.
20. For keys, the best height is and the worst ; over random orders the measured heights ran from to , with a mean of .