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 Binary Search Tree (BST) — a specialised binary tree that maintains elements in sorted order, enabling efficient searching, insertion, and deletion. BSTs are a core topic in A-Level Computer Science.
A Binary Search Tree is a binary tree with the following ordering property:
For every node N:
This property holds for every node in the tree, not just the root.
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
For node 8: all left subtree values (1, 3, 4, 6, 7) < 8, and all right subtree values (10, 13, 14) > 8.
To search for a value in a BST:
FUNCTION search(node, target) RETURNS BOOLEAN
IF node = NULL THEN
RETURN FALSE
ELSE IF target = node.data THEN
RETURN TRUE
ELSE IF target < node.data THEN
RETURN search(node.left, target)
ELSE
RETURN search(node.right, target)
END IF
END FUNCTION
def search(node, target) -> bool:
if node is None:
return False
if target == node.data:
return True
elif target < node.data:
return search(node.left, target)
else:
return search(node.right, target)
Searching for 6 in the BST above:
Only 3 comparisons needed for a tree with 8 nodes.
| Operation | Average Case | Worst Case |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
The average case assumes a balanced tree where each comparison eliminates half the remaining nodes (like binary search on a sorted array).
The worst case occurs when the tree is degenerate (skewed) — essentially a linked list, requiring n comparisons.
Balanced BST (O(log n)): Degenerate BST (O(n)):
8 1
/ \ \
3 10 3
/ \ \ \
1 6 14 6
\
8
Exam Tip: When discussing BST performance, always mention both the average (O(log n)) and worst (O(n)) cases. Explain that the worst case occurs when elements are inserted in sorted order, creating a degenerate tree.
To insert a new value:
FUNCTION insert(node, value) RETURNS NODE
IF node = NULL THEN
RETURN NEW TreeNode(value)
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
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.