A levels Computer Science · Algorithms
Graph and tree traversal
1Depth-first traversal
A depth-first traversal goes as far as possible along one branch before backtracking. It uses a stack (or recursion).
def dfs(graph, v, visited):
visited.append(v)
for n in graph[v]:
if n not in visited:
dfs(graph, n, visited)
return visited
Two traversals from A, taking neighbours in alphabetical order. Depth-first follows one branch to its end; breadth-first goes level by level.
Uses: finding a path through a maze, checking whether a graph is connected, and finding cycles.
Check yourself
Which data structure does depth-first traversal use?
Show the answer
A stack
Backtrack to the latest.
2Breadth-first traversal
A breadth-first traversal visits all the neighbours of a vertex before moving further away. It uses a queue.
- Put the start vertex in the queue and mark it visited.
- Remove the vertex at the front and visit it.
- Add each unvisited neighbour to the back of the queue and mark it.
- Repeat until the queue is empty.
Breadth-first from A in the graph above
- Queue [A]. Visit A; add B, C.
- Visit B; add D, E. Visit C; add F (E is already marked).
- Visit D, E, F. Order: A, B, C, D, E, F.
In an unweighted graph, breadth-first finds the path with the fewest edges, so it is used for shortest routes in social networks ("degrees of separation").
Check yourself
Why does breadth-first traversal find the path with the fewest edges?
Show the answer
It visits all vertices one edge away, then two edges away, and so on
Layer by layer.
3Tree traversals
Binary trees have three depth-first traversals:
| Traversal | Order | Use |
|---|---|---|
| pre-order | root, left, right | copying a tree; prefix (Polish) notation |
| in-order | left, root, right | outputting a BST in sorted order |
| post-order | left, right, root | deleting a tree; reverse Polish notation |
An expression tree for (3 + 4) × 2. Its three traversals give prefix, infix and postfix (reverse Polish) notation.
A quick trick: draw a line round the tree starting left of the root. Pre-order lists each node as you pass its left side, in-order its underneath, post-order its right side.
Check yourself
Which traversal outputs a binary search tree in ascending order?
Show the answer
In-order
Left, root, right.
4Reverse Polish notation
In reverse Polish notation (RPN, or postfix), operators come after their operands: 3 + 4 becomes 3 4 +. It needs no brackets.
Evaluating RPN with a stack:
- Read left to right.
- If it is a number, push it.
- If it is an operator, pop two numbers, apply the operator, and push the result.
3 4 + 2 *
- Push 3, push 4.
- + : pop 4 and 3, push 7.
- Push 2.
- * : pop 2 and 7, push 14.
RPN is used in some calculators and in the way compilers and interpreters evaluate expressions.
Check yourself
What is the value of 5 1 2 + 4 * + ?
Show the answer
17
1+2=3, 3×4=12, 5+12.
5Converting between notations
Infix to RPN
- (6 − 2) × (1 + 3): convert each bracket first.
- 6 − 2 → 6 2 −. 1 + 3 → 1 3 +.
- Combine with × at the end: 6 2 − 1 3 + ×.
| Infix | RPN |
|---|---|
| a + b × c | a b c × + |
| (a + b) × c | a b + c × |
| a × (b − c) / d | a b c − × d / |
An expression tree can be traversed post-order to give RPN directly.
Check yourself
What is (a + b) / c in RPN?
Show the answer
a b + c /
Bracket first.
6Comparing depth-first and breadth-first
| Depth-first | Breadth-first | |
|---|---|---|
| structure | stack or recursion | queue |
| order | one branch to its end | level by level |
| finds shortest path (unweighted)? | no | yes |
| memory | usually less (one branch) | can be large (whole level) |
| typical use | mazes, cycles, connectivity | shortest routes, web crawlers |
Both visit every vertex and edge once: O(V + E) with an adjacency list.
Check yourself
Which traversal is best for finding the fewest-edges route between two people in a social network?
Show the answer
Breadth-first
Layer by layer.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera