Binary Search Trees
Node Based Data Structures
- Root: the topmost node
j. By convention we draw it at the top. - Parent and child:
jis the parent ofmandb; they are children ofj. - Descendants: all nodes reachable below a given node.
- Ancestors: all nodes on the path from a given node back to the root.
- Leaf: a node with no children.
Trees have levels. Each level is one step further from the root.
A tree is balanced when the left and right subtrees contain roughly the same number of nodes. This should apply for most nodes, maintaining this balance matters for performance.
When trees are imbalanced, they effectively turn into a linked list. This is the worst case in performance for a binary search tree.
Binary Search Trees
A binary tree is a tree where each node has a maximum of two children: a left child and a right child.
A binary search tree (BST) is a binary tree that is ordered with an invariant as follows:
- Each node has at most one left child and one right child.
- All values in a node's left subtree are less than the node's value.
- All values in a node's right subtree are greater than the node's value.
Below is a binary tree, but not a valid BST. The root has two children that are not strictly less-than on the left and greater-than on the right.
Uses for BSTs
- Storing key-value pairs or unique items while keeping them ordered
- Range queries for finding values between a range using the property that subtrees can be skipped
- Ordered traversal for yielding elements in sorted order
- Finding predecessors or successors of a value
Implementing a BST Node
A Node can be implemented with a simple class that contains a left and right attribute. We could add more features to this class such as using a setter to ensure that the BST ordering conditions are met when setting the value of the children.
class Node:
def __init__(
self,
value: int,
left: "Node | None" = None,
right: "Node | None" = None,
):
self.value = value
self.left_child = left
self.right_child = right
We can build a small tree:
node1 = Node(25)
node2 = Node(75)
root = Node(50, node1, node2)
Search
We can use recursivley traverse the BST to find values quickly by using the property that the nodes on the left always contain values less than the current value, and larger values on the right.
Given this BST, we can find 61 by:
- Starting at the root.
- If the current node holds the target value, we are done.
- If the target is less than the current node, move to the left child.
- If the target is greater, move to the right child.
- Repeat until the value is found or we reach a dead end (None).
At each step we eliminate roughly half of the remaining nodes. This is the same principle behind binary search on an ordered array.
Python Search Implementation
A BST search can be implemented by traversing either the left or right hand branch if we have not found the value in the current node.
def search(value, node: Node) -> Node | None:
if not node:
return None
if node.value == value:
return node
if search_value < node.value:
return search(value, node.left_child)
else:
return search(value, node.right_child)
- Two base cases: we found the value, or we have reached
None - Each comparison moves down one level and discards the other subtree
- Search takes \(O(h)\) time, where \(h\) is the height of the tree
Iterative Version
def search(search_value, node: Node) -> Node | None:
while node and node.value != search_value:
node = node.left_child if search_value < node.value else node.right_child
return node
- Same \(O(h)\) time, but only \(O(1)\).
- Safe on very deep trees, where recursion could hit Python's recursion limit.
Insertion
Insertion into a BST requires searching for an appropriate position then a single attachment step.
- Search for where the new value would belong by following the BST rules.
- When you reach a node that has no child in the required direction, attach the new value at that position.
Python Insertion Implementation
The base case is reaching an empty child slot. Otherwise, we recurse deeper into the tree.
def insert(value, node: Node) -> None:
if value < node.value:
if not node.left_child:
node.left_child = Node(value)
else:
insert(value, node.left_child)
elif value > node.value:
if not node.right_child:
node.right_child = Node(value)
else:
insert(value, node.right_child)
- Insertion into a BST is \(O(log N)\): a search plus one attachment.
- Insertion into an ordered array is \(O(N)\)
- A binary search to find the position, then shifting all subsequent elements one place to the right.
Order of Insertion
If we insert already-sorted data (e.g. 1, 2, 3, 4, 5), the tree degenerates. This essentially a creates a linked list. We lose efficiency gains and search becomes \(O(N)\).
If we insert the same values in a different order (e.g. 3, 2, 4, 1, 5), we get a balanced tree:
- Search is expected \(O(log N)\) again
- Randomly ordered input gives expected height \(O(\log N)\), but with no guarantee
- Picking the middle element as the root and partitioning each half will give us a balanced tree in \(O(N)\)
- The process is very similar to a binary search
- Self-balancing trees (such as red-black trees) handle this automatically
def build_balanced_bst(values: list) -> Node | None:
# Sort values first
values = sorted(values)
def build(start: int, end: int) -> Node | None:
if start > end:
return None
# Find the middle element index
mid = (start + end) // 2
return Node(
values[mid], # Start with middle value node
left=build(start, mid - 1), # Recurse left
right=build(mid + 1, end), # Recurse right
)
return build(0, len(values) - 1)
Deletion
There are three specific cases we need to handle when deleting a node:
- The node to delete has no children (a leaf).
- The node to delete has one child.
- The node to delete has two children.
No Children
Remove the node from the parent if there are no children. To remove 4, which is a leaf, the rest of the tree stays intact.
One Child
Delete the node and promote its child into its place. To delete 10, the child (11) takes the position of its deleted parent.
Two Children
Replace the value of the node being deleted with the value of a neighbouring node in sorted order, then remove that neighbour from its original position. There are two valid choices:
- In-order successor: the smallest value in the right subtree. Go to the right child, then keep going left until there is no left child.
- In-order predecessor: the largest value in the left subtree. Go to the left child, then keep going right until there is no right child.
Either choice keeps the BST property, because the replacement is greater than everything in the left subtree and smaller than everything in the right subtree.
The successor has no left child and the predecessor has no right child, so each has at most one child to promote. If it has one, that child takes its former position.
To delete 50 using the in-order successor:
- Right child of 50 is 75
- Keep going left: 56, then 52
- 52 has no left child, so it is the successor
- Copy 52 into 50's position, then remove the original 52 node
Python Deletion Implementation
The main delete function recursively searches for the node, then handles each case.
def find_min_node(node):
"""Go left until we get to the end"""
while node.left_child:
node = node.left_child
return node
def delete(value_to_delete, node):
# Base case: value not found in tree
if node is None:
return None
# Search phase: recurse left or right to find node to delete
if value_to_delete < node.value:
# The node want to delete is towards the left
node.left_child = delete(value_to_delete, node.left_child)
elif value_to_delete > node.value:
# The node want to delete is towards the right
node.right_child = delete(value_to_delete, node.right_child)
# Replace the value of the node we found to delete
else:
# Case 1: no children (leaf node)
if not node.left_child and not node.right_child:
return None
# Case 2: one child: return the child to replace this node
elif not node.left_child:
return node.right_child
elif not node.right_child:
return node.left_child
# Case 3: two children: replace value with in-order successor
else:
# Find successor node by staring from right child
successor = find_min_node(node.right_child)
# Copy successor's value into this node
node.value = successor.value
# Delete the successor from the right subtree
node.right_child = delete(successor.value, node.right_child)
return node
In-Order Traversal
Suppose we store we store book titles from a library in a BST and we want to traverse each title in order.
# Build the BST
root = Node("Pachinko")
insert("The God of Small Things", root)
insert("Half of a Yellow Sun", root)
insert("Homegoing", root)
insert("The Nightingale", root)
insert("The House in the Cerulean Sea", root)
To visit every node in sorted order, we use in-order traversal:
- Recursively traverse the left subtree.
- Visit the current node.
- Recursively traverse the right subtree.
The base case is reaching None (a non-existent child).
def traverse(node):
if not node:
return
traverse(node.left_child)
print(node.value)
traverse(node.right_child)
traverse_and_print(root)
Half of a Yellow Sun Homegoing Pachinko The God of Small Things The House in the Cerulean Sea The Nightingale
The titles print in alphabetical order because a BST keeps smaller values on the left and larger on the right. Traversal visits every node exactly once, so it runs in \(O(N)\) time.
Full Implementation
- The recursive functions need a
nodeargument, so the methods call an_method withself.root - This could be replaced with a default argument to the
nodethat gets replaced withself.rootas well
Summary
- A binary search tree stores data in a node-based structure where left descendants are smaller and right descendants are larger
- Search, insertion, and deletion are all \(O(log N)\) when the tree is balanced
- In-order traversal visits nodes in sorted order in \(O(N)\) time
- The order of insertion affects the tree's shape and therefore its performance
- BSTs are suited for applications that require sorted data with frequent updates
When should you consider something else?
- If you rarely modify data, an ordered list is simpler and has better performance
- If ordering is not needed, a dictionary is faster for search, insert, and delete
Exercises
Use the following code to complete the exercises:
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left_child = left
self.right_child = right
def insert(value, node):
if value < node.value:
if not node.left_child:
node.left_child = Node(value)
else:
insert(value, node.left_child)
elif value > node.value:
if not node.right_child:
node.right_child = Node(value)
else:
insert(value, node.right_child)
root = Node(50)
insert(25, root)
insert(75, root)
insert(10, root)
insert(33, root)
insert(56, root)
insert(89, root)
Counting Nodes
Write a Python method count_nodes(node) that returns the total number of nodes in a BST.
The structure is very similar to traverse, but instead of printing, you are counting.
Finding Minimum and Maximum Values
The BST invariant tells us something useful: the smallest value in the tree is always as far left as possible, and the largest is always as far right as possible.
Write two functions:
def find_min(node):
"""Return the smallest value in the BST."""
...
def find_max(node):
"""Return the largest value in the BST."""
...
You should get the following output
find_min(root) # should return 10
find_max(root) # should return 89
Nodes at a Given Depth
Write a function nodes_at_depth(node, depth) that returns a list of all values at a given depth in the tree. The root is at depth 0, its children are at depth 1, and so on.
def nodes_at_depth(node, depth):
...
Test your function on the same tree:
nodes_at_depth(root, 0) # [50]
nodes_at_depth(root, 1) # [25, 75]
nodes_at_depth(root, 2) # [10, 33, 56, 89]
Think about what happens to depth as you recurse. What is the base case?