Sub topic 4
Searching by following the ordering
This chapter assumes you know recursion and loops, introductory Big-O, and how to build a small class with references. It also assumes you have seen the binary search tree (BST) ordering property: for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger.
The working model
Search asks one question: is key in the tree? Because of the ordering property, each comparison at a node rules out one whole subtree.
At a node with key k, there are three outcomes:
key == k: found. Return this node.key < k: every key in the right subtree is larger thank, sokeycannot be there. Move left.key > k: move right.
If you reach None, the key is absent. The empty position you reached is also where an insertion of that key would go, which the next chapter uses.
Iterative implementation
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def search(node, key):
while node is not None and node.key != key:
node = node.left if key < node.key else node.right
return nodeThe loop stops in one of two cases. Either node is None (not found), or node.key == key (found). In both cases node holds the answer, so return node covers both. The caller gets a Node or None.
Here is the function on a tree built by hand:
root = Node(50)
root.left = Node(30)
root.right = Node(70)
root.right.left = Node(60)
print(search(root, 60) is not None) # True
print(search(root, 65) is not None) # False
print(search(None, 10)) # NoneSearching for 65 goes 50, right to 70, left to 60, right to None. That is three comparisons for a tree of four keys.
A recursive version
The recursive form mirrors the definition. It is shorter to read, but it uses one stack frame per level.
def search_recursive(node, key):
if node is None or node.key == key:
return node
if key < node.key:
return search_recursive(node.left, key)
return search_recursive(node.right, key)Python does not optimize tail calls, so on a very deep tree the recursive version can hit the recursion limit. The loop does not.
Cost
Each step moves down one level and does constant work. Search therefore takes time proportional to the length of the path, which is at most the tree's height h. The cost is O(h). The loop uses O(1) extra space. The recursive version uses O(h).
Height depends on the shape of the tree, not just the number of keys. A well-spread tree with n keys has height about log n. A tree built from sorted input can have height n - 1, and then search is as slow as scanning a linked list. A later chapter covers this.
Common errors
- Dereferencing
None. Writingnode.keybefore checkingnode is not NoneraisesAttributeError. The loop condition checksNonefirst, andandshort-circuits. - Treating the result as a boolean. A found
Nodeis truthy by default, but if you later define__len__or__bool__onNode, that can change. Compare withis not None. - Searching a tree that is not a valid BST. Search trusts the ordering property. If a key sits in the wrong subtree, search can miss it and return
None. - Comparing mixed types. Keys must be mutually comparable. Mixing
intandstrraisesTypeErroron the first comparison between them.
Exercise
Starting from a root with key 50 and the tree 50 -> (left 30, right 70), 70 -> (left 60, right 80), how many key comparisons does search(root, 80) make, and what does the cost depend on in general?
Show answer
It compares against 50 (go right), 70 (go right), and 80 (equal), so 3 comparisons. In general the cost depends on the length of the path from the root, which is at most the tree's height h, so search is O(h).
Exercise
Why does the loop in search use node.key != key after node is not None in the while condition, and what happens if you swap the two tests?
Show answer
and short-circuits, so node.key is only read when node is not None. If you swap the tests, reaching an empty position evaluates None.key and raises AttributeError.