You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers the core operations on Binary Search Trees (BSTs) — insertion, deletion, and searching — as required by the OCR A-Level Computer Science (H446) specification. These operations are fundamental to understanding how tree-based data structures work.
To search for a value in a BST, start at the root and use the ordering property to decide whether to go left or right.
function search(node, value)
if node == null then
return false
end if
if value == node.data then
return true
else if value < node.data then
return search(node.left, value)
else
return search(node.right, value)
end if
end function
def search(node, value):
if node is None:
return False
if value == node.data:
return True
elif value < node.data:
return search(node.left, value)
else:
return search(node.right, value)
Search for 6 in this BST:
8
/ \
3 10
/ \ \
1 6 14
/ \
4 7
| Step | Current Node | Comparison | Action |
|---|---|---|---|
| 1 | 8 | 6 < 8 | Go left |
| 2 | 3 | 6 > 3 | Go right |
| 3 | 6 | 6 == 6 | Found! |
Number of comparisons: 3 (compared with O(n) = 9 for linear search)
| Case | Complexity | When |
|---|---|---|
| Best | O(1) | Value is at the root |
| Average | O(log n) | Tree is reasonably balanced |
| Worst | O(n) | Tree is degenerate (all nodes on one side) |
Insertion always adds a new node as a leaf — it never restructures the existing tree.
function insert(node, value)
if node == null then
node = new TreeNode(value)
return node
end if
if value < node.data then
node.left = insert(node.left, value)
else if value > node.data then
node.right = insert(node.right, value)
end if
return node
end function
def insert(node, value):
if node is None:
return TreeNode(value)
if value < node.data:
node.left = insert(node.left, value)
elif value > node.data:
node.right = insert(node.right, value)
return node
Insert 5 into this BST:
8
/ \
3 10
/ \
1 6
| Step | Current Node | Comparison | Action |
|---|---|---|---|
| 1 | 8 | 5 < 8 | Go left |
| 2 | 3 | 5 > 3 | Go right |
| 3 | 6 | 5 < 6 | Go left |
| 4 | null | - | Insert 5 here |
Result:
8
/ \
3 10
/ \
1 6
/
5
Deletion is the most complex BST operation because removing a node must preserve the BST ordering property. There are three cases.
Simply remove the node by setting its parent's pointer to null.
Example: Delete 1 from the BST:
Before: After:
8 8
/ \ / \
3 10 3 10
/ \ / \
1 6 _ 6
Replace the node with its only child. The child takes the deleted node's position.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.