OCR H446, section 2.3.1 (e)
This point is about the algorithms that operate on data structures: how to add, remove, search and visit items. (The structures themselves are in 1.4.2.)
Stacks
A stack is last in, first out (LIFO). Items are added and removed at one end (the top).
| Operation | Meaning |
|---|---|
| push(item) | Add to the top |
| pop() | Remove and return the top item |
| peek() | Look at the top item without removing it |
| isEmpty() | True if there are no items |
| isFull() | True if there's no room (a fixed-size stack) |
class Stack:
def __init__(self, size):
self.items = [None] * size
self.top = -1 # -1 means empty
def is_empty(self):
return self.top == -1
def is_full(self):
return self.top == len(self.items) - 1
def push(self, item):
if self.is_full():
raise OverflowError("stack full")
self.top += 1
self.items[self.top] = item
def pop(self):
if self.is_empty():
raise IndexError("stack empty")
item = self.items[self.top]
self.top -= 1
return item
Uses: the call stack for subroutines, undo, back button, evaluating expressions (reverse Polish), backtracking, depth-first search. All operations are .
Queues
A queue is first in, first out (FIFO). Items are added at the rear and removed from the front.
| Operation | Meaning |
|---|---|
| enqueue(item) | Add to the rear |
| dequeue() | Remove and return the front item |
| isEmpty() / isFull() | Test the state |
A linear queue in an array wastes space as the front moves along. A circular queue wraps round using MOD:
class CircularQueue:
def __init__(self, size):
self.items = [None] * size
self.front = 0
self.count = 0
def enqueue(self, item):
if self.count == len(self.items):
raise OverflowError("queue full")
rear = (self.front + self.count) % len(self.items)
self.items[rear] = item
self.count += 1
def dequeue(self):
if self.count == 0:
raise IndexError("queue empty")
item = self.items[self.front]
self.front = (self.front + 1) % len(self.items)
self.count -= 1
return item
Uses: print queues, keyboard buffers, scheduling of processes, and breadth-first search.
Linked lists
A linked list is a chain of nodes. Each node holds data and a pointer to the next node. A head pointer marks the start. The last node's pointer is null (None).
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_front(self, data): # O(1)
node = Node(data)
node.next = self.head
self.head = node
def traverse(self): # O(n)
current = self.head
while current is not None:
print(current.data)
current = current.next
def search(self, target): # O(n)
current = self.head
while current is not None:
if current.data == target:
return True
current = current.next
return False
def delete(self, target): # O(n) to find
previous = None
current = self.head
while current is not None:
if current.data == target:
if previous is None:
self.head = current.next
else:
previous.next = current.next
return True
previous = current
current = current.next
return False
Inserting or deleting only needs pointers changed, with no shifting of items. But there's no direct access by index: you must follow the links.
Binary trees
A binary tree has nodes, each with at most two children (left and right). A binary search tree (BST) keeps smaller values on the left and larger on the right of each node.
Adding to a BST
Start at the root. Go left if the new value is smaller, right if larger, until you find an empty place.
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(node, value):
if node is None:
return TreeNode(value)
if value < node.value:
node.left = insert(node.left, value)
else:
node.right = insert(node.right, value)
return node
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)
A balanced BST can be searched in . A badly unbalanced one (data added in order) is a list, with search.
Traversing a tree
Traversal means visiting every node once.
Depth-first: post-order
A depth-first traversal goes all the way down a branch before moving to the next. When it reaches a node with no unvisited children, it backtracks to the previous node, and carries on from the last node that still has unvisited children. Post-order visits left subtree, right subtree, then the node itself.
def post_order(node):
if node is not None:
post_order(node.left)
post_order(node.right)
print(node.value)
For the tree above, the output is 1 6 3 14 10 8.
Compare the three orders (all depth-first):
| Order | Visit | Result for the tree above | Typical use |
|---|---|---|---|
| Pre-order | node, left, right | 8 3 1 6 10 14 | Copying a tree |
| In-order | left, node, right | 1 3 6 8 10 14 | Sorted output from a BST |
| Post-order | left, right, node | 1 6 3 14 10 8 | Deleting a tree, evaluating expressions (gives reverse Polish) |
Depth-first uses recursion (the call stack) or an explicit stack.
Breadth-first
A breadth-first traversal visits level by level, from the root down, left to right. It uses a queue:
from collections import deque
def breadth_first(root):
queue = deque([root])
while queue:
node = queue.popleft() # dequeue
print(node.value)
if node.left:
queue.append(node.left) # enqueue
if node.right:
queue.append(node.right)
For the same tree, the output is 8 3 10 1 6 14.
| Depth-first | Breadth-first | |
|---|---|---|
| Order | Down a branch first | Level by level |
| Uses | Stack or recursion | Queue |
| Good for | Exploring all paths, maze solving, expression trees | Shortest path (fewest edges), nearest first |
| Time |
Worked example
Task: the tree below is traversed. Give the post-order and breadth-first outputs.
- Post-order (left, right, node): for 20, do the left subtree (12): its left is 5, its right is 15, then 12. Then the right subtree (30): its right is 40, then 30. Then 20. Output: 5, 15, 12, 40, 30, 20.
- Breadth-first (level by level): level 1: 20. Level 2: 12, 30. Level 3: 5, 15, 40. Output: 20, 12, 30, 5, 15, 40.
Exam tip: learn the order of each traversal and which structure each uses (depth-first: stack/recursion; breadth-first: queue). For post-order, remember "the node comes last". When writing stack or queue code, always check for empty and full first.
Check yourself
What is the difference between a stack and a queue?
A stack is last in, first out, and works at one end (the top). A queue is first in, first out, adding at the rear and removing from the front.
Why is a circular queue better than a linear queue in an array?
It reuses the space freed at the front by wrapping the pointers round, so space isn't wasted.
What is the advantage of a linked list over an array for insertion?
Items needn't be shifted; only a couple of pointers are changed.
In what order does post-order traversal visit the nodes?
Left subtree, then right subtree, then the node itself.
Which data structure does breadth-first traversal use?
A queue.