Edexcel International Advanced Level Computer Science, point 14.1.4
Definition
A tree is a hierarchical data structure made of nodes connected by edges, with no cycles. One node is the root (at the top), and each node can have child nodes. It is a connected graph (14.1.3) with no cycles.
Function and why needed
Trees store data with a natural hierarchy (folders and files, family trees, organisation charts, HTML pages) and let us search, sort and insert quickly (binary search trees, expression trees, decision trees).
a. Structure
| Term | Meaning |
|---|---|
| Root | The top node (no parent) |
| Parent / child | A node and the nodes directly below it |
| Leaf | A node with no children |
| Subtree | A node together with all its descendants |
| Edge | A link between a parent and a child |
| Depth / height | Distance from the root / the longest path to a leaf |
| Siblings | Nodes with the same parent |
b. Types
Binary tree
A tree in which each node has at most two children, a left child and a right child.
Binary search tree (BST)
A binary tree with an ordering rule: for every node, all values in its left subtree are smaller, and all values in its right subtree are larger. (Duplicates are usually not allowed, or go to one side.)
This ordering makes searching fast.
Representing a tree in code
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
(Or an array: for a node at index , left child at , right child at .)
c. Operations (binary search tree)
Insert
Start at the root. If the new value is smaller, go left. If larger, go right. Repeat until you find an empty place, and put the new node there.
def insert(node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = insert(node.left, value)
elif value > node.value:
node.right = insert(node.right, value)
return node
root = None
for v in [8, 3, 10, 1, 6, 14]:
root = insert(root, v)
Trace of inserting 6 into the tree: 6 < 8, go left to 3. 6 > 3, go right: empty, so 6 becomes 3's right child.
Search
Compare with the current node: equal: found; smaller: go left; larger: go right; no node: not found.
def search(node, target):
if node is None:
return False
if target == node.value:
return True
if target < node.value:
return search(node.left, target)
return search(node.right, target)
print(search(root, 6)) # True (path: 8, 3, 6)
print(search(root, 7)) # False
Each step discards a whole subtree. In a balanced tree, the time is . In a badly unbalanced tree (for example data inserted in sorted order), the tree becomes a line and the time is .
Delete
Find the node, then there are three cases:
| Case | What to do |
|---|---|
| 1. A leaf | Remove it (set the parent's pointer to null) |
| 2. One child | Replace the node with its child |
| 3. Two children | Replace its value with the in-order successor (the smallest value in its right subtree), then delete that successor (which has at most one child) |
def smallest(node):
while node.left is not None:
node = node.left
return node
def delete(node, value):
if node is None:
return None
if value < node.value:
node.left = delete(node.left, value)
elif value > node.value:
node.right = delete(node.right, value)
else: # found the node to delete
if node.left is None:
# leaf, or only a right child
return node.right
if node.right is None:
return node.left # only a left child
successor = smallest(node.right) # two children
node.value = successor.value
node.right = delete(node.right, successor.value)
return node
Example: delete 3 (which has two children, 1 and 6). The in-order successor is 6 (the smallest in the right subtree). Copy 6 into the node, then remove the old 6. Result: 3's position holds 6, with child 1.
Traverse
Visiting every node once. Three depth-first orders (recursive):
| Order | Visit | Use |
|---|---|---|
| Pre-order | Node, left, right | Copying a tree, prefix expressions |
| In-order | Left, node, right | Gives a BST's values in sorted order |
| Post-order | Left, right, node | Deleting a tree, postfix (reverse Polish) expressions |
def pre_order(node):
if node:
print(node.value, end=" ")
pre_order(node.left)
pre_order(node.right)
def in_order(node):
if node:
in_order(node.left)
print(node.value, end=" ")
in_order(node.right)
def post_order(node):
if node:
post_order(node.left)
post_order(node.right)
print(node.value, end=" ")
For the tree with root 8 (left 3 with children 1 and 6, right 10 with right child 14):
| Traversal | Output |
|---|---|
| Pre-order | 8 3 1 6 10 14 |
| In-order | 1 3 6 8 10 14 (sorted) |
| Post-order | 1 6 3 14 10 8 |
Breadth-first (level-order) traversal uses a queue and visits level by level: 8, 3, 10, 1, 6, 14.
Benefits
- Fast search, insert and delete in a balanced BST ().
- Natural for hierarchical data.
- In-order traversal gives sorted data without a separate sort.
- Dynamic size.
Drawbacks
- Can become unbalanced (worst case ), which needs self-balancing trees (AVL, red-black) to prevent.
- More memory than an array (two pointers per node).
- More complex to code (recursion and deletion).
- No direct access by index.
Worked example
Task: insert 50, 30, 70, 20, 40, 60 into an empty BST, then give the in-order and post-order traversals, and find the path to search for 60.
Building the tree:
- 50 is the root.
- 30 < 50: left of 50. 70 > 50: right of 50.
- 20 < 50, < 30: left of 30. 40 < 50, > 30: right of 30.
- 60 > 50, < 70: left of 70.
- In-order: 20, 30, 40, 50, 60, 70 (sorted).
- Post-order: 20, 40, 30, 60, 70, 50.
- Search for 60: 50 (60 > 50, right), 70 (60 < 70, left), 60: found (3 comparisons, against up to 6 in a list).
Exam tip: write the traversal order as a rule (pre: node first, in: node in the middle, post: node last) and apply it recursively. In-order on a BST gives sorted output. For deletion, name the three cases. Mention that balance affects speed.
Check yourself
What is the rule that makes a binary search tree?
For every node, values in its left subtree are smaller and values in its right subtree are larger.
What does an in-order traversal of a binary search tree produce?
The values in sorted (ascending) order.
What is a leaf node?
A node with no children.
Why can the search time of a binary search tree become O(n)?
If the tree is unbalanced (for example data inserted in sorted order), it forms a line, so each step removes only one node.
Give the post-order traversal of a tree with root 5, left child 2 and right child 8
2, 8, 5.