Worked solution from the Computational thinking and Problem-solving Paper 3 Advanced Theory booklet, Part 1 of 2.
Each node has a left pointer, data and a right pointer. Add Yellow, Orange, Indigo and Violet and draw an arrow from each parent's correct pointer box to its child. Every node with no child uses -1. RootPtr points to Red.
| Node | LeftPtr | RightPtr |
|---|---|---|
| Red | arrow to Green | arrow to Yellow |
| Green | arrow to Blue | arrow to Orange |
| Yellow | arrow to Violet | -1 |
| Blue | -1 | -1 |
| Orange | arrow to Indigo | -1 |
| Indigo | -1 | -1 |
| Violet | -1 | -1 |
Four additional nodes (Yellow, Orange, Indigo, Violet) with correct data [1]
Correct -1 null pointers in all added nodes and no extra ones where an arrow goes to a node [1]
Correct arrows joining each parent to its child [1]
All nodes in the correct places with nothing extra written in the pointer boxes [1]
Number the nodes by their index. A pointer holds the index of the child, and -1 means no child. FreePtr points to the first unused row, index 7.
| Index | LeftPtr | Data | RightPtr |
|---|---|---|---|
| 0 | 1 | Red | 2 |
| 1 | 3 | Green | 4 |
| 2 | 6 | Yellow | -1 |
| 3 | -1 | Blue | -1 |
| 4 | 5 | Orange | -1 |
| 5 | -1 | Indigo | -1 |
| 6 | -1 | Violet | -1 |
| 7 |
Write 7 in FreePtr (row 7 stays blank).
Red and Green rows correct [1]
Yellow and Blue rows correct [1]
Orange, Indigo and Violet rows correct [1]
FreePtr = 7 with row 7 blank [1]
Start at the root. If the item is smaller than the node's data, go left; if larger, go right; if equal, return the index.
FUNCTION SearchTree(Item : STRING) RETURNS INTEGER
NowPtr ← RootPtr
WHILE NowPtr <> -1
IF BinTree[NowPtr].Data > Item THEN
NowPtr ← BinTree[NowPtr].LeftPtr
ELSE
IF BinTree[NowPtr].Data < Item THEN
NowPtr ← BinTree[NowPtr].RightPtr
ELSE
RETURN NowPtr
ENDIF
ENDIF
ENDWHILE
RETURN NowPtr
ENDFUNCTIONRETURNS INTEGER [1]
NowPtr ← RootPtr [1]
BinTree[NowPtr].Data > Item [1]
NowPtr ← BinTree[NowPtr].RightPtr [1]
▶ Topic lesson
A lesson on this topic · by rjmcompsci. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.