Sub topic 13
Searching and Inserting in a BST
This chapter assumes you know the binary search tree (BST) property: every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger. It also assumes you can read recursive Python and know Big-O notation.
One path from the root
The BST property means each comparison rules out a whole subtree. Search and insert both start at the root and compare the target key with the current node:
- If the key is smaller, go left.
- If the key is larger, go right.
- If the key is equal, you have found it. Search returns the node, and insert changes nothing.
- If the next child is empty, search has failed. Insert puts the new node in that empty spot.
Because the walk never branches, it visits at most one node per level. The cost is proportional to the tree's height.
Implementation
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def inorder(node):
if node is None:
return []
return inorder(node.left) + [node.value] + inorder(node.right)
def bst_insert(root, key):
if root is None:
return Node(key)
if key < root.value:
root.left = bst_insert(root.left, key)
elif key > root.value:
root.right = bst_insert(root.right, key)
return root
def bst_search(root, key):
while root is not None and root.value != key:
root = root.left if key < root.value else root.right
return root
bst = None
for k in [5, 3, 8, 1, 4, 9]:
bst = bst_insert(bst, k)
print(inorder(bst)) # [1, 3, 4, 5, 8, 9]
print(bst_search(bst, 4) is not None) # True
print(bst_search(bst, 7) is not None) # Falsebst_insert is recursive and returns the root of the (possibly new) subtree. The caller reassigns the result, as in root.left = bst_insert(root.left, key). This reassignment is how a new node gets linked into its parent. bst_search is iterative because it never needs to come back up the path.
Tracing a failed search
Searching for 7 in the tree built above follows this path:
A failed search ends at the exact spot where an insert would attach the new node. That is why the two operations share one walk.
Common errors
- Dropping the return value. If you write
bst_insert(root.left, key)without assigning the result, inserting into an empty child does nothing. - Duplicates. The code above ignores equal keys. If you need to store duplicates, decide on a rule, such as a count field on each node. Sending equal keys to one side breaks the strict form of the property.
- Assuming O(log n). The cost is O(h), where h is the height. A random insertion order gives a height near log n. Sorted input gives a degenerate tree, a chain in which h is n - 1, so both operations take O(n).
- Recursion limits. Recursive insert on a chain of thousands of nodes can hit Python's recursion limit. Write insert iteratively, or use a self-balancing tree, when input order is not under your control.
Exercise
You insert the keys 1, 2, 3, 4 in that order into an empty BST. What does the tree look like, and what is the worst-case cost of searching it?
Show answer
Each new key is larger than every key already present, so it always goes to the right child. The tree is a right-leaning chain with height 3. Searching for 4 compares against all four nodes, so search costs O(n), not O(log n).