Sub topic 9
Searching a BST
This chapter covers how to search a binary search tree (BST) for a key, and how to find its minimum, maximum, successor, and predecessor. It assumes you know recursion, object references, Big-O notation, and the BST property: for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger. This tutorial's examples assume distinct keys.
Why the BST property makes search fast
In an unordered binary tree, finding a key means visiting nodes until you hit it, which can take O(n) time. The BST property lets you discard an entire subtree after one comparison.
At a node with key k, compare the target x with k:
- If
x == k, the search succeeds. - If
x < k,xcan only be in the left subtree. The whole right subtree is ruled out. - If
x > k,xcan only be in the right subtree. The whole left subtree is ruled out.
The search therefore follows a single root-to-leaf path. It never branches.
The search algorithm
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def search(node, key):
while node and node.key != key:
node = node.left if key < node.key else node.right
return nodeThe loop stops in one of two ways:
nodeisNone. The key is absent, because you walked off the bottom of the tree.node.key == key. The function returns that node.
The function returns the node itself, not a boolean. Callers can test search(root, 7) is not None for membership, or use the returned node to read or change its data.
A recursive version is equivalent:
def search_rec(node, key):
if node is None or node.key == key:
return node
if key < node.key:
return search_rec(node.left, key)
return search_rec(node.right, key)Both versions do the same comparisons. The recursion is a tail call, so the iterative form is a direct translation. In Python the iterative form is safer because it uses no call-stack space and cannot hit the recursion limit on a tall tree. This matters in GATE questions about space: iterative search uses O(1) extra space, and recursive search uses O(h) stack space, where h is the tree height.
A worked trace
Build the BST by inserting the keys 50, 30, 70, 20, 40, 60, 80, 65 in that order.
Search for 65:
| Step | Current node | Comparison | Move |
|---|---|---|---|
| 1 | 50 | 65 > 50 | go right |
| 2 | 70 | 65 < 70 | go left |
| 3 | 60 | 65 > 60 | go right |
| 4 | 65 | 65 == 65 | found |
That took 4 comparisons for a tree of 8 nodes. Now search for 55:
| Step | Current node | Comparison | Move |
|---|---|---|---|
| 1 | 50 | 55 > 50 | go right |
| 2 | 70 | 55 < 70 | go left |
| 3 | 60 | 55 < 60 | go left |
| 4 | None | not found |
An unsuccessful search ends at a None pointer. That empty slot is exactly where 55 would be inserted. This link between failed search and insertion is why the next chapter's insertion code looks so similar to search.
Minimum and maximum
The smallest key is in the leftmost node, and the largest key is in the rightmost node. The reason is the BST property: if a node has a left child, everything in that left subtree is smaller than the node, so the node cannot be the minimum.
def minimum(node):
while node.left:
node = node.left
return node
def maximum(node):
while node.right:
node = node.right
return nodeBoth functions assume node is not None. In the example tree, minimum(root) follows 50, 30, 20 and returns 20. maximum(root) follows 50, 70, 80 and returns 80.
Note that the minimum need not be a leaf. A node with only a right child can be the minimum. For instance, if 20 had a right child 25, then 20 would still be the minimum of the whole tree, but it would not be a leaf.
Successor and predecessor
The inorder successor of a node is the node with the next larger key. The predecessor is the node with the next smaller key. Both are needed for BST deletion, which a later chapter covers.
There are two cases for the successor of a node x:
- If
xhas a right subtree, the successor is the minimum of that subtree. - Otherwise, the successor is the lowest ancestor of
xwhose left subtree containsx. Walk up until you arrive from a left child.
Without parent pointers, you can find the successor from the root by searching for x and remembering the last node where you turned left:
def successor(root, key):
succ = None
node = root
while node:
if key < node.key:
succ = node
node = node.left
elif key > node.key:
node = node.right
else:
if node.right:
return minimum(node.right)
return succ
return NoneThe variable succ holds the most recent ancestor from which the search went left. Such an ancestor is larger than key, and the last one recorded is the closest.
Examples from the tree above:
- Successor of 30: 30 has a right subtree rooted at 40, whose minimum is 40. Answer: 40.
- Successor of 40: 40 has no right child. The search went left at 50 only, so
succis 50. Answer: 50. - Successor of 65: 65 has no right child. The search went left at 70, so
succis 70. Answer: 70. - Successor of 80: no right child, and the search never went left. Answer:
None.
The predecessor is symmetric: swap left and right, and minimum and maximum.
Cost of search
Each loop iteration moves down one level, so the number of comparisons is at most h + 1, where h is the height counted in edges. The worst case is O(h).
| Case | Situation | Comparisons |
|---|---|---|
| Best | Key is at the root | 1 |
| Average (random insertion order) | Tree height is about 2 ln n on average | O(log n) |
| Worst | Skewed tree, key at the bottom or absent | n |
The value of h depends on the insertion order. Inserting 1, 2, 3, 4, 5 in sorted order gives a right-skewed tree, which is a linked list with h = n − 1. Searching for 5 then takes 5 comparisons, and search is O(n). Inserting 3, 1, 5, 2, 4 gives a shorter tree with h = 2. The later chapter on balanced trees addresses this problem.
Common errors
- Dereferencing
None. Callingminimum(None)raises anAttributeError. Check for an empty tree first. - Comparing with the wrong child. If you write
node.right if key < node.key, the search goes the wrong way and reports missing keys that are present. - Using
if node.key == keyinside the loop without aNonecheck. The loop conditionnode and ...must testnodefirst, or the final step crashes on a missing key. - Assuming search visits all nodes on a level. It visits exactly one node per level.
- Confusing "visited nodes" with "path length". A path of d edges means d + 1 nodes and d + 1 comparisons for a successful search at depth d.
Typical GATE question patterns
- Valid search sequences. Given a BST and several sequences, decide which could be the order of nodes visited while searching for a key. The valid sequences must follow one path, so keys visited must narrow the range monotonically. If the sequence is 50, 70, 60, 65 for the target 65, every key after 70 must be below 70, and every key after 60 must be above 60.
- Counting comparisons. Count the nodes on the path, and add one if the question counts the final
Nonecheck separately. Read the question for the convention. - Minimum or maximum location. The answer is always the leftmost or rightmost node, found by following only left or only right pointers.
- Successor of a leaf. Walk up to the first ancestor reached from a left child.
Checking a search sequence
To test whether a sequence is a valid search path for a target, keep an interval (lo, hi) that starts as (-inf, +inf). After each node k in the sequence, if the target is smaller than k, set hi = k. Otherwise set lo = k. Every later key must lie strictly inside (lo, hi).
def valid_search_path(seq, target):
lo, hi = float("-inf"), float("inf")
for k in seq:
if not (lo < k < hi):
return False
if target < k:
hi = k
elif target > k:
lo = k
return True
print(valid_search_path([50, 70, 60, 65], 65)) # True
print(valid_search_path([50, 70, 60, 55], 65)) # False
print(valid_search_path([50, 30, 60, 65], 65)) # FalseThe second call fails because 55 is not greater than 60 once the search moved right at 60. The third call fails because 60 is not below 30 after the search moved left at 30... more precisely, after 65 > 50 the lower bound is 50, then 30 is outside (50, inf), so it is rejected immediately.
Summary of costs
| Operation | Time | Extra space (iterative) |
|---|---|---|
| Search | O(h) | O(1) |
| Minimum | O(h) | O(1) |
| Maximum | O(h) | O(1) |
| Successor | O(h) | O(1) |
| Predecessor | O(h) | O(1) |
Exercise
A BST is built by inserting 40, 20, 60, 10, 30, 50, 70, 25 in that order. (a) List the nodes visited when searching for 25. (b) List the nodes visited when searching for 55. (c) What is the inorder successor of 30?
Show answer
The tree has root 40, children 20 and 60, then 10 and 30 under 20, 50 and 70 under 60, and 25 as the left child of 30. (a) 40, 20, 30, 25: go left at 40, right at 20, left at 30, then found. (b) 40, 60, 50, then None: go right at 40, left at 60, right at 50, which is empty, so 55 is absent. (c) 30 has no right child, and the search for 30 goes left only at 40, so the successor is 40.
Exercise
A BST contains the keys 1 to 100. A search for 55 is run. Which of these could be the sequence of visited keys: (i) 50, 70, 52, 60, 55; (ii) 50, 70, 52, 54, 55; (iii) 50, 40, 55? Explain.
Show answer
Track the interval. (i) After 50 the interval is (50, inf). After 70 it is (50, 70). After 52 it is (52, 70). After 60 it is (52, 60). Then 55 is inside, so the sequence is valid. (ii) After 50, 70, 52 the interval is (52, 70). Then 54 is inside, and since 55 > 54 the interval becomes (54, 70). Then 55 is inside, so the sequence is valid. (iii) After 50 the interval is (50, inf), and 40 lies outside it, so the sequence is invalid. Valid: (i) and (ii).
Exercise
What is the worst-case number of key comparisons to search for a key in a BST with n nodes, and what insertion order produces it?
Show answer
The worst case is n comparisons, when the key is at the deepest node of a skewed tree or is absent and larger or smaller than all keys on the path. Inserting the keys in strictly increasing or strictly decreasing order produces a skewed tree with height n − 1.