Edexcel International Advanced Level Computer Science, point 18.2.7
The binary search tree (BST) was described in 14.1.4. In Unit 4 you must write one in code, represented with classes or references, and handle it with insert, find and traverse. Check the PLS for details.
Rule: for every node, values in the left subtree are smaller and values in the right subtree are larger.
a. Represent
With classes
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
With references (parallel lists)
Lists hold the value, and the index of the left and right child (-1 for none):
values = [8, 3, 10, 1, 6, 14]
left = [1, 3, -1, -1, -1, -1] # index of each node's left child
right = [2, 4, 5, -1, -1, -1] # index of each node's right child
root = 0
# 8 (index 0)
# / \
# 3 (1) 10 (2)
# / \ \
# 1 (3) 6 (4) 14 (5)
The same shape in two forms. Classes are clearer; references work without objects.
b. Handle
Insert
Start at the root. If the new value is smaller, go left; if larger, go right; place it at the first empty position. Equal values are ignored (or sent to one side).
def insert(self, value):
node = Node(value)
if self.root is None:
self.root = node
return
current = self.root
while True:
if value < current.value:
if current.left is None:
current.left = node
return
current = current.left
elif value > current.value:
if current.right is None:
current.right = node
return
current = current.right
else:
return # already there
(A recursive version, shown in 14.1.4, is shorter.)
Find
Follow the same path, comparing at each node.
def find(self, target):
current = self.root
while current is not None:
if target == current.value:
return True
if target < current.value:
current = current.left
else:
current = current.right
return False
Traverse
Visit every node (18.2.8), here in-order (sorted output):
def in_order(self):
result = []
def visit(node):
if node:
visit(node.left)
result.append(node.value)
visit(node.right)
visit(self.root)
return result
Test and trace
tree = BST()
for v in [8, 3, 10, 1, 6, 14]:
tree.insert(v)
print(tree.in_order()) # [1, 3, 6, 8, 10, 14]
print(tree.find(6), tree.find(7)) # True False
tree.insert(8) # a duplicate: ignored
print(tree.in_order()) # unchanged
Trace: insert 6 into the tree after 8, 3, 10 and 1.
| Step | Compare | Direction |
|---|---|---|
| Root 8 | 6 < 8 | left |
| Node 3 | 6 > 3 | right |
| 3's right is empty | 6 becomes 3's right child |
Search for 6 takes 3 comparisons (8, 3, 6), instead of up to 6 in a list.
Test cases: an empty tree, one node, a duplicate, a value smaller than all, larger than all, a missing value, inserting in sorted order (gives a lopsided tree).
line = BST()
for v in [1, 2, 3, 4, 5]:
# each node goes to the right: a "linked list"
line.insert(v)
An unbalanced tree is slow ( to search): insert in a random order (or use a self-balancing tree) to keep it bushy.
Worked example
Task: build a BST from the words ["pear", "apple", "mango", "zebra", "kiwi"] and check whether "kiwi" and "fig" are in it.
words = BST()
for w in ["pear", "apple", "mango", "zebra", "kiwi"]:
words.insert(w)
# ['apple', 'kiwi', 'mango', 'pear', 'zebra']
print(words.in_order())
print(words.find("kiwi"), words.find("fig")) # True False
Shape: pear is the root. apple < pear: left. mango < pear, > apple: right of apple. zebra > pear: right. kiwi < pear, > apple, < mango: left of mango.
Searching for kiwi: pear (left), apple (right), mango (left), kiwi found (4 comparisons). Searching for fig: pear (left), apple (right), mango (left), kiwi (fig < kiwi, left is empty): not found.
Exam tip: trace insertion by writing the comparison at each node. Remember that duplicates need a rule. Be able to draw the tree from a list of values inserted in order, and say what in-order traversal gives (sorted values).
Check yourself
Where does a new value go in a binary search tree?
At the first empty position found by going left if it is smaller and right if it is larger at each node.
What does an in-order traversal of a BST give?
The values in sorted order.
What happens if values are inserted in sorted order?
The tree becomes a line (every node goes to the right), so searching is slow, O(n).
How can a tree be represented without objects?
With lists holding each node's value and the index of its left and right child (with -1 for none).