🔒 Pro · Component 2 · 2.3.1 Algorithms
2.3.1e Tree Traversal and Dijkstra's Algorithm
OCR H446 · A Level Computer Science · ~22 min read
Notes
Video
Slides
Worksheet
Quiz

Binary Trees — Recap

A binary tree is a rooted tree where each node has at most two children: left and right. A Binary Search Tree (BST) additionally enforces: left child < parent < right child. Tree traversal visits all nodes systematically — three DFS-based orders are used.

Example tree used throughout:

        4
       / \
      2   6
     / \ / \
    1  3 5  7

Pre-Order Traversal (Root → Left → Right)

Visit the current node FIRST, then traverse the left subtree, then the right subtree. Produces a top-down view. Used for copying/serialising a tree.

function preOrder(node)
    if node = None then return
    process(node)              // Visit ROOT first
    preOrder(node.left)        // Then LEFT
    preOrder(node.right)       // Then RIGHT
endfunction

Pre-order on example tree: 4, 2, 1, 3, 6, 5, 7

Mnemonic: R-L-R (Root, Left, Right) — "Pre" = root first (pre-fix notation)

In-Order Traversal (Left → Root → Right)

Traverse the left subtree, then visit the current node, then traverse the right subtree. Visits nodes in sorted ascending order for a BST — used for BST sorting and displaying values in order.

function inOrder(node)
    if node = None then return
    inOrder(node.left)         // LEFT first
    process(node)              // Then ROOT
    inOrder(node.right)        // Then RIGHT
endfunction

In-order on example tree: 1, 2, 3, 4, 5, 6, 7 (sorted!)

Mnemonic: L-R-R (Left, Root, Right) — "In" = root in-between

Post-Order Traversal (Left → Right → Root)

Traverse left subtree, then right subtree, then visit the current node LAST. Used for deleting a tree (children before parents) and evaluating expression trees (leaves before operators).

function postOrder(node)
    if node = None then return
    postOrder(node.left)       // LEFT first
    postOrder(node.right)      // Then RIGHT
    process(node)              // ROOT last
endfunction

Post-order on example tree: 1, 3, 2, 5, 7, 6, 4

Mnemonic: L-R-R (Left, Right, Root) — "Post" = root last (post-fix notation)

Summary of Tree Traversals

TraversalOrderResult on exampleApplication
Pre-orderRoot → Left → Right4,2,1,3,6,5,7Copy/serialise tree, prefix expressions
In-orderLeft → Root → Right1,2,3,4,5,6,7BST sorted output, validating BST
Post-orderLeft → Right → Root1,3,2,5,7,6,4Delete tree (children first), postfix expressions

Dijkstra's Shortest Path Algorithm

Dijkstra's algorithm finds the shortest path from a single source to all other vertices in a weighted graph with non-negative edge weights. It is a greedy algorithm — always processes the vertex with the currently smallest known distance.

Key Requirements

Non-negative edge weights (no negative costs). Weighted graph (directed or undirected). Uses a priority queue (min-heap) for efficiency: always processes the nearest unvisited vertex next.

Algorithm

function dijkstra(graph, source)
    dist ← dictionary, all vertices = ∞
    dist[source] ← 0
    prev ← dictionary (to reconstruct path)
    unvisited ← priority queue of (distance, vertex)
    enqueue (0, source) to unvisited

    while unvisited not empty
        (d, u) ← dequeue minimum from unvisited    // greedy choice
        for each neighbour v of u with edge weight w
            alt ← dist[u] + w
            if alt < dist[v] then        // found shorter path
                dist[v] ← alt
                prev[v] ← u
                enqueue (alt, v) to unvisited
            endif
        next v
    endwhile
    return dist, prev
endfunction

Worked Example

Graph: A→B(4), A→C(2), C→B(1), B→D(5), C→D(8), B→E(3), D→E(2)

StepCurrentdist[A]dist[B]dist[C]dist[D]dist[E]
Start0
Process AA (d=0)042
Process CC (d=2)03 (2+1)210
Process BB (d=3)0328 (3+5)6 (3+3)
Process EE (d=6)03286
Process DD (d=8)03286

Shortest paths from A: to B=3 (A→C→B), C=2, D=8 (A→C→B→D), E=6 (A→C→B→E)

Complexity

ImplementationTime Complexity
Simple (array)O(V²)
Binary heap + adjacency listO((V + E) log V)
Fibonacci heapO(V log V + E)

Why Dijkstra's is Greedy

At each step, Dijkstra's processes the vertex with the minimum tentative distance — the locally optimal (greedy) choice. Because all edge weights are non-negative, once a vertex is processed its distance is final — no shorter path can be found later. This greedy property is proven by induction and relies on non-negative weights (with negative weights, a processed vertex's distance might be improved later, breaking the algorithm).

Exam tip: Tree traversal mnemonics — Pre: R-L-R (root first); In: L-R-R (root middle, gives sorted BST output); Post: L-R-R-Root (root last). In-order on BST always gives ascending sorted order — this is the most likely exam question.
Exam tip: Dijkstra's always processes the unvisited vertex with the SMALLEST current distance. Show a table with all distances, update when a shorter path is found. Cannot handle negative edge weights. Applications: GPS shortest route, network routing protocols (OSPF).
✓ Notes completed!
Video coming soon
Click to advance · Arrow keys also work
Click slide or press arrow keys to navigate

Worksheet — 2.3.1e Tree Traversal & Dijkstra

8 questions · 24 marks · instantly marked

Q1For the binary tree with root 8, left child 3 (left:1, right:6), right child 10 (right:14), write the pre-order, in-order, and post-order traversals.[3 marks]
✓ Mark scheme
Tree: 8 root; 3 left (children: 1, 6); 10 right (right child: 14).
Pre-order (Root-Left-Right): 8, 3, 1, 6, 10, 14 [1]
In-order (Left-Root-Right): 1, 3, 6, 8, 10, 14 [1] — note: gives sorted ascending order, confirming this is a BST
Post-order (Left-Right-Root): 1, 6, 3, 14, 10, 8 [1]
Q2Explain why in-order traversal of a Binary Search Tree always produces the elements in ascending sorted order.[2 marks]
✓ Mark scheme
In a BST: all nodes in the left subtree of a node N have values less than N, and all in the right subtree are greater [1]. In-order traversal visits left subtree (all values < N) first, then N, then right subtree (all values > N). Recursively: all left values are visited in sorted order, then N, then all right values in sorted order. The result is all values processed in ascending order [1].
Q3State one application of post-order traversal and explain why post-order (not pre- or in-order) is appropriate for it.[2 marks]
✓ Mark scheme
Application: deleting a tree OR evaluating expression trees [1]. Post-order is appropriate for deletion because children must be deleted before their parent — if the parent is deleted first, pointers to children are lost, causing memory leaks. Post-order processes children (leaves first) before the root → children always deleted before parents [1]. OR: expression trees: operator nodes appear above operand nodes. Post-order evaluates both subtrees (operands) before the operator → operands available when operator is processed (gives postfix/RPN evaluation).
Q4Explain the greedy choice made at each step of Dijkstra's algorithm. Why does this greedy approach give the correct answer?[3 marks]
✓ Mark scheme
Greedy choice: at each step, select the unvisited vertex with the smallest current tentative distance (nearest unprocessed vertex) [1]. This is locally optimal — the minimum-distance unvisited node is always processed next. Correctness: once a vertex is processed (dequeued with minimum distance), its distance is FINAL because all remaining unvisited vertices have distances ≥ current vertex's distance [1]. Any path to the current vertex through another unvisited vertex would be current_dist + additional_edge_weight > current_dist (since edge weights are non-negative). So no shorter path can be found later [1].
Q5Trace Dijkstra's algorithm from A on the graph: A→B(6), A→C(2), C→B(2), B→D(1), C→D(5). Show the distance table at each step.[4 marks]
✓ Mark scheme
Init: dist={A:0, B:∞, C:∞, D:∞} [0.5]
Process A (d=0): dist[B] = min(∞,0+6)=6; dist[C] = min(∞,0+2)=2 → dist={A:0, B:6, C:2, D:∞} [1]
Process C (d=2): dist[B] = min(6,2+2)=4; dist[D] = min(∞,2+5)=7 → dist={A:0, B:4, C:2, D:7} [1]
Process B (d=4): dist[D] = min(7,4+1)=5 → dist={A:0, B:4, C:2, D:5} [1]
Process D (d=5): no updates [0.5]
Shortest paths: A→B=4 (A→C→B), A→C=2, A→D=5 (A→C→B→D)
Q6Why does Dijkstra's algorithm fail when the graph contains negative edge weights? Give an example to illustrate.[3 marks]
✓ Mark scheme
Dijkstra's assumes once a vertex is processed (given its current minimum distance), that distance is final. This is only true for non-negative weights [1]. With negative edges: a path discovered later via a negative edge could be shorter than a previously processed vertex's distance. Example: A→B(5), A→C(2), C→B(-10). Dijkstra processes A (dist=0), then B (dist=5) — marks B as final. Later processes C (dist=2), finds A→C→B = 2 + (-10) = -8 < 5, but B is already marked visited → B's distance stays 5 (wrong answer = -8) [2].
Q7Write the recursive pre-order traversal algorithm in pseudocode. Identify the base case and explain how recursion implements the traversal.[3 marks]
✓ Mark scheme
function preOrder(node)
  if node = None then return // base case [1]
  process(node) // visit ROOT
  preOrder(node.left) // recurse left [0.5]
  preOrder(node.right) // recurse right [0.5]
endfunction
Base case: node = None (null pointer — leaf's child, or empty tree). Recursion: each call processes the current node, then makes two recursive calls for left and right children. The call stack naturally manages the order — left subtree fully processed before right. When a leaf is reached, both recursive calls immediately return (node.left = None, node.right = None). Stack unwinds back to parent [1].
Q8Compare Dijkstra's algorithm with BFS. When would you use BFS and when would you use Dijkstra's for finding shortest paths?[4 marks]
✓ Mark scheme
BFS uses a FIFO queue and finds shortest path in terms of EDGES (fewest hops) in an UNWEIGHTED graph [1]. All edges are treated as equal cost (weight 1). BFS is simpler and runs in O(V+E). Use BFS when: edges have no weights / all equal weights; you want fewest hops rather than minimum cost [1]. Dijkstra's uses a priority queue (min-heap) and finds shortest path by TOTAL EDGE WEIGHT in a WEIGHTED graph [1]. Processes vertices in order of increasing distance. Complexity O((V+E) log V). Use Dijkstra's when: edges have different weights (costs/distances/times); you want minimum total cost path — GPS routing, network shortest path [1].
Topic Quiz
1 of 15
You scored
out of 15
🎯

Mini Test — 2.3.1e Tree Traversal & Dijkstra

  • 10 questions · 10 marks · 10 minutes
  • 5 MCQ + 5 short answer
Card 1 of 15
Click to reveal
🎉
Complete!
TermDefinition
🔒
Pro Content
Subscribe to access all 69 OCR H446 A Level lessons.
£7.99/month
or £59/year
Subscribe now →
← 2.3.1d Graph Traversal: BFS & DFS 2.3.1 Algorithms 🎉 All lessons complete! Dashboard →