Binary Search Trees
A binary search tree (BST) is a binary tree with one ordering rule, which must hold at every node:
All values in a node's left subtree are smaller than the node, and all values in its right subtree are larger.
This is binary search turned into a data structure. To find a value, compare it with the root: smaller means go left, larger means go right. Each comparison discards a whole subtree. Unlike a sorted array, a BST also supports fast insertion and deletion, since nothing needs to shift.
Insert and search
Inserting follows the same path as a search and attaches the new value where the search falls off the tree. Step through building a BST and then searching for 31 (present) and 70 (absent):
class Node:
def __init__(self, value):
self.value = value
self.left = self.right = None
def insert(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert(root.left, value)
elif value > root.value:
root.right = insert(root.right, value)
return root # duplicates are ignored
def search(root, target):
path = []
node = root
while node is not None:
path.append(node.value)
if target == node.value:
return True, path
node = node.left if target < node.value else node.right
return False, path
root = None
for v in [50, 28, 73, 14, 35, 66, 91, 31]:
root = insert(root, v)
for target in [31, 70]:
found, path = search(root, target)
print(f"search {target}: found={found}, compared with {path}")search 31: found=True, compared with [50, 28, 35, 31]
search 70: found=False, compared with [50, 73, 66]
Searching for 31 compares with 50, 28, 35 and finds it: the same path as the animation. Searching for 70 goes right at 50, left at 73, right at 66, and falls off the tree.
The tree it builds:
50
/ \
28 73
/ \ / \
14 35 66 91
/
31Minimum, maximum and sorted order
The smallest value is the leftmost node; the largest is the rightmost. An in-order traversal lists all values sorted.
class Node:
def __init__(self, value):
self.value, self.left, self.right = value, None, None
def insert(root, value):
if root is None:
return Node(value)
if value < root.value: root.left = insert(root.left, value)
elif value > root.value: root.right = insert(root.right, value)
return root
def minimum(node):
while node.left:
node = node.left
return node.value
def maximum(node):
while node.right:
node = node.right
return node.value
def inorder(node):
return inorder(node.left) + [node.value] + inorder(node.right) if node else []
root = None
for v in [50, 28, 73, 14, 35, 66, 91, 31]:
root = insert(root, v)
print(minimum(root), maximum(root), inorder(root))14 91 [14, 28, 31, 35, 50, 66, 73, 91]
Deleting a node
Deleting has three cases:
- Leaf (no children): just remove it.
- One child: replace the node by its child.
- Two children: find the in-order successor (the smallest value in the right subtree), copy its value into the node, then delete the successor from the right subtree. The successor has no left child, so that second deletion is case 1 or 2.
class Node:
def __init__(self, value):
self.value, self.left, self.right = value, None, None
def insert(root, value):
if root is None:
return Node(value)
if value < root.value: root.left = insert(root.left, value)
elif value > root.value: root.right = insert(root.right, value)
return root
def delete(root, value):
if root is None:
return None
if value < root.value:
root.left = delete(root.left, value)
elif value > root.value:
root.right = delete(root.right, value)
else:
if root.left is None: # cases 1 and 2
return root.right
if root.right is None:
return root.left
succ = root.right # case 3: leftmost of the right subtree
while succ.left:
succ = succ.left
root.value = succ.value
root.right = delete(root.right, succ.value)
return root
def preorder(node):
return [node.value] + preorder(node.left) + preorder(node.right) if node else []
root = None
for v in [50, 28, 73, 14, 35, 66, 91, 31]:
root = insert(root, v)
print("start: ", preorder(root))
root = delete(root, 14); print("delete 14: ", preorder(root)) # a leaf
root = delete(root, 35); print("delete 35: ", preorder(root)) # one child (31)
root = delete(root, 50); print("delete 50: ", preorder(root)) # two childrenstart: [50, 28, 14, 35, 31, 73, 66, 91]
delete 14: [50, 28, 35, 31, 73, 66, 91]
delete 35: [50, 28, 31, 73, 66, 91]
delete 50: [66, 28, 31, 73, 91]
Deleting the root 50 copies its successor, 66 (the smallest value in the right subtree), into the root.
The shape problem
A BST's speed depends on its height. Inserting values in random order gives a height of about 2 log₂ n on average. Inserting them in sorted order builds a degenerate chain, and every operation becomes O(n):
class Node:
def __init__(self, value):
self.value, self.left, self.right = value, None, None
def insert(root, value): # iterative, so deep trees don't overflow the stack
new = Node(value)
if root is None:
return new
node = root
while True:
side = "left" if value < node.value else "right"
child = getattr(node, side)
if child is None:
setattr(node, side, new)
return root
node = child
def height(node):
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
mixed = [(k * 37) % 101 for k in range(101)] # 0..100 in a scrambled order
sorted_values = list(range(101))
for name, values in [("scrambled", mixed), ("sorted", sorted_values)]:
root = None
for v in values:
root = insert(root, v)
print(f"{name:>9} insertion of 101 values: height {height(root)}")scrambled insertion of 101 values: height 10
sorted insertion of 101 values: height 100
A perfectly balanced tree of 101 nodes would have height 6. The fix is a self-balancing tree, such as the AVL tree in the next lesson.
Complexity
| Operation | Balanced BST | Degenerate BST |
|---|---|---|
| Search, insert, delete | O(log n) |
O(n) |
| Min / max | O(log n) |
O(n) |
| In-order traversal | O(n) |
O(n) |
Test yourself
In a BST, where is the smallest value?
- At the root
- At the leftmost node
- At the rightmost node
- At any leaf
When deleting a node with two children, which value replaces it?
- Its left child
- The root
- Its in-order successor (smallest value in the right subtree)
- The largest value in the tree
What happens if you insert 1, 2, 3, ..., 1000 into an empty BST in that order?
- A perfectly balanced tree
- A chain of height 999, so operations become O(n)
- An error
- A tree of height 10