Sub topic 7
Finding the Minimum and Maximum
This chapter assumes you can read the Node class and the search function from the earlier chapters, and that you are comfortable with loops and with the idea that a BST keeps smaller keys on the left and larger keys on the right.
The idea
The ordering property gives a direct way to find the smallest and largest keys. Every key in a node's left subtree is smaller than the node. So the smallest key in a tree can never have a left child. If it did, the left child would be smaller still.
The same argument works in the other direction. The largest key never has a right child.
- Minimum: start at the root and keep moving to the left child until there is none.
- Maximum: start at the root and keep moving to the right child until there is none.
You never compare keys. The shape of the tree already tells you where to go.
Implementation
The loop below reuses the Node class and insert function from earlier. It returns the node, not just the key, because later operations such as deletion and successor need the node itself.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def minimum(node):
while node.left is not None:
node = node.left
return node
def maximum(node):
while node.right is not None:
node = node.right
return node
root = None
for k in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, k)
print(minimum(root).key) # 20
print(maximum(root).key) # 80Both functions use a loop with no recursion. The recursive version is also correct, but the loop avoids extra stack frames and is just as clear.
Starting from a subtree
Both functions take any node, not only the root. Calling minimum(node) returns the smallest key in the subtree rooted at that node. This matters because deletion relies on it. When you delete a node with two children, you call minimum(node.right) to find the in-order successor, which is the smallest key larger than the node's key.
subtree = root.right # the subtree rooted at 70
print(minimum(subtree).key) # 60
print(maximum(subtree).key) # 80Cost
Each step moves one level down, so the loop runs at most as many times as the tree is tall. The cost is O(h), where h is the height.
| Tree shape | Height | Cost of min or max |
|---|---|---|
| Balanced, n keys | about log n | O(log n) |
| Chain of n keys | n - 1 | O(n) |
In a chain built from sorted input, the minimum is found at once if the chain leans right, but the maximum needs n - 1 steps. The reverse is true for a chain that leans left. Either way, the worst case is O(n).
Common errors
- Calling on an empty tree.
minimum(None)fails with anAttributeError, becauseNonehas noleftattribute. Check for an empty tree before calling, or decide that the function should returnNone. - Following the wrong child. Swapping
leftandrightreturns the other extreme. A quick test with a small tree catches this. - Assuming the minimum is a leaf. The minimum has no left child, but it can have a right child. In a tree with 20 as the minimum, 20 might still have a right child such as 25. Deletion of the minimum must handle that case.
- Returning the key when you need the node. If you return only the key, you cannot later unlink the node or read its right subtree.
Exercise
A BST is built by inserting 40, 20, 60, 10, 30, 25 in that order. What are the minimum and maximum keys, and how many child links does the search for the minimum follow?
Show answer
The minimum is 10 and the maximum is 60. The search for the minimum starts at 40, moves left to 20, then left to 10, so it follows 2 links. The maximum is found by moving right once, from 40 to 60.
Exercise
Why can the minimum node of a subtree still have a child, and which child can it have?
Show answer
The minimum has no left child, because a left child would hold a smaller key. It can have a right child, because right-subtree keys are larger and do not affect which key is smallest. Deletion of such a node returns its right subtree in its place.