Data structures · 3 / 15 Theory

Binary search trees

A tree is a structure of nodes organised hierarchically: there is a root node and each node can have children. They appear everywhere: the folder system, the HTML of a web page, mathematical expressions. Here we look at the most famous one: the binary search tree (BST).

The BST rule

Each node has at most two children, left and right, and satisfies: all the values in the left subtree are smaller than the node, and all those in the right one are greater. Thanks to that, searching for a value is like binary search: at each step you discard half of the tree.

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

Insert

Insertion is naturally recursive: compare with the current node and go down the left or right until you find a gap.

def insert(node, value):
    if node is None:
        return Node(value)
    if value < node.value:
        node.left = insert(node.left, value)
    elif value > node.value:
        node.right = insert(node.right, value)
    return node          # duplicates are ignored

root = None
for v in [50, 30, 70, 20, 40, 60, 80]:
    root = insert(root, v)

The resulting tree is:

#          50
#        /    #      30      70
#     /  \    /  #    20  40  60  80

Search

def search(node, value):
    while node is not None:
        if value == node.value:
            return True
        node = node.left if value < node.value else node.right
    return False

print(search(root, 40))   # True
print(search(root, 55))   # False

Traversal: in order

The in-order traversal (*inorder*) visits the left child first, then the node and finally the right one. In a BST it produces the values sorted. With yield from it is very short.

def inorder(node):
    if node is not None:
        yield from inorder(node.left)
        yield node.value
        yield from inorder(node.right)

print(list(inorder(root)))   # [20, 30, 40, 50, 60, 70, 80]

Height, minimum and maximum

def height(node):
    if node is None:
        return 0
    return 1 + max(height(node.left), height(node.right))

def minimum(node):
    while node.left is not None:
        node = node.left
    return node.value

print(height(root))   # 3
print(minimum(root))  # 20

The minimum is always in the leftmost node and the maximum in the rightmost. Put it all into practice with Binary search tree.

Balanced and degenerate trees

If you insert the values already sorted (1, 2, 3, 4, 5), each node only has a right child and the tree becomes a linked list of height 5: searching is no longer fast. A balanced tree with *n* nodes has a height close to log₂(n), which is why searching among a million values takes about 20 steps. There are variants that rebalance themselves (AVL, red-black), but implementing them is outside the scope of this course.

degenerate = None
for v in [1, 2, 3, 4, 5]:
    degenerate = insert(degenerate, v)
print(height(degenerate))   # 5  (instead of 3)