CIE AS & A Level Computer Science, section 19.1 (Algorithms)
What a binary tree is
A binary tree is a structure of nodes, where each node has at most two children, a left and a right. The top node is the root; a node with no children is a leaf.
In a binary search tree, for every node, items in the left subtree are smaller and items in the right subtree are larger.
Implementation
Each node stores data, a left pointer and a right pointer, in arrays or as records.
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
def search(root, value):
while root is not None:
if value == root.value:
return True
root = root.left if value < root.value else root.right
return False
root = None
for v in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, v)
print(search(root, 60), search(root, 65)) # True False
The tree built is:
Traversals
| Traversal | Order | Result for the tree |
|---|---|---|
| In-order | left, root, right | 20, 30, 40, 50, 60, 70, 80 (sorted) |
| Pre-order | root, left, right | 50, 30, 20, 40, 70, 60, 80 |
| Post-order | left, right, root | 20, 40, 30, 60, 80, 70, 50 |
def in_order(node):
if node:
in_order(node.left)
print(node.value, end=" ")
in_order(node.right)
in_order(root) # 20 30 40 50 60 70 80
Uses
In-order gives a sorted list. Pre-order can copy a tree. Post-order is used to delete a tree or evaluate expressions (as in postfix notation). A balanced tree is searched in .
Common mistake: traversing in the wrong order. Remember that the name says where the root goes: pre (root first), in (root in the middle), post (root last). Also, a tree built from sorted data becomes a long chain, which is slow to search.
Exam tip: when asked to insert values, take them in order and compare with each node going left (smaller) or right (larger). Draw the tree and then give the traversal.
Check yourself
What is the in-order traversal of a binary search tree?
The items in sorted order.
Where is a new value smaller than the root placed?
In the left subtree.
What is a leaf node?
A node that has no children.