Sub topic 5
Quick Review: Binary Search Trees
This chapter assumes you have seen binary search trees (BSTs) before. You should be comfortable with recursion, Big-O notation, and short Python programs. The aim is to refresh the parts of a BST that interval trees depend on, and to point out the errors that matter later.
The ordering rule
A binary search tree is a binary tree in which every node holds a key. For every node, all keys in its left subtree are smaller than the node's key, and all keys in its right subtree are larger than or equal to it. Each node has at most two children, called left and right.
This rule applies to the whole subtree, not only to the immediate children. A node in the left subtree of the root must be smaller than the root, even if it sits five levels down. Mistaking this for a "parent is bigger than its left child" rule is a common source of bugs.
The ordering rule lets you discard half of the remaining candidates (when the tree is reasonably balanced) at each comparison. That is the property the interval tree reuses. In an interval tree the key is an interval's low endpoint, so the same rule decides where each interval goes.
An example tree
Inserting 15, 10, 17, 5, 12, 30 in that order produces this tree.
Every key left of 15 (10, 5, 12) is smaller than 15, and every key right of 15 (17, 30) is larger. The same holds inside each subtree.
Core operations
The code below implements insertion, search, in-order traversal, and height. Equal keys go to the right subtree. The interval tree code later in this tutorial makes the same choice, so duplicate low endpoints are handled consistently.
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)
else:
node.right = insert(node.right, key)
return node
def search(node, key):
while node is not None:
if key == node.key:
return node
node = node.left if key < node.key else node.right
return None
def in_order(node, out):
if node is not None:
in_order(node.left, out)
out.append(node.key)
in_order(node.right, out)
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
root = None
for k in [15, 10, 17, 5, 12, 30]:
root = insert(root, k)
keys = []
in_order(root, keys)
print(keys) # [5, 10, 12, 15, 17, 30]
print(search(root, 12) is not None) # True
print(search(root, 13) is not None) # False
print(height(root)) # 3Three details in this code are worth noticing.
insertreturns the root of the subtree it was given, and the caller assigns that result back tonode.leftornode.right. This pattern lets the function create a new node when it reachesNone. It also gives you a natural place to update extra data on the way back up the recursion, which is exactly what the augmentation in later chapters does.searchis iterative because it never needs to come back up the tree. Insertion is recursive here because it does need to return through every ancestor.- Height is counted in nodes, so an empty tree has height 0 and a single node has height 1. Some textbooks count edges instead. Check which convention a source uses before comparing bounds.
In-order traversal returns sorted keys
An in-order traversal visits the left subtree, then the node, then the right subtree. On a valid BST it produces the keys in sorted order, as the output [5, 10, 12, 15, 17, 30] shows. This gives you a cheap correctness check. If a traversal of your tree is not sorted, some insertion or rotation has broken the ordering rule.
Cost depends on height
Insert and search each follow one path from the root toward a leaf, so their cost is proportional to the height h of the tree, written O(h). The height is not fixed by the number of keys n. It depends on the insertion order.
| Shape of tree | Height | Insert and search cost |
|---|---|---|
| Perfectly balanced | about log2(n) | O(log n) |
| Random insertion order (on average) | O(log n) | O(log n) |
| Keys inserted already sorted | n | O(n) |
The last row is the failure mode. Inserting 1, 2, 3, and so on makes every new key go right, and the tree becomes a linked list. You can see it directly.
chain = None
for k in range(1, 201):
chain = insert(chain, k)
print(height(chain)) # 200A tree of 200 keys with height 200 gives no speedup over a list. The interval tree inherits this weakness, because it is a BST keyed on low endpoints. Real interval data is often sorted, for example events logged in time order, so this case is common rather than exotic.
Common errors
- Checking only parent and child. A tree where each node is ordered against its children can still violate the rule across levels. For example, a node 12 placed in the right subtree of 15 and then given a left child 11 passes the local check but breaks the global one. Validate with an in-order traversal, or pass lower and upper bounds down the recursion.
- Forgetting to reassign the result of a recursive insert. Writing
insert(node.left, key)withoutnode.left = ...silently loses the new node whenever the child wasNone. - Treating duplicates inconsistently. If insertion sends equal keys right but a search or deletion assumes they go left, some keys become unreachable. Pick one rule and apply it everywhere.
- Assuming O(log n) without balancing. The bound holds only when the height is logarithmic. Without a balancing scheme, treat O(h) as the honest cost.
What the interval tree will change
A plain BST answers "is this exact key present?" by following one path. An interval tree needs a different question answered: "does any stored interval overlap this one?" The ordering rule alone cannot answer that, because a node's key tells you nothing about the high endpoints in its subtrees. The next chapters fix this by storing one extra value in each node and keeping it correct as the tree changes. The structure stays a BST, and its height still controls the cost.
Exercise
You insert the keys 8, 3, 10, 1, 6, 14 into an empty BST (equal keys would go right). What does an in-order traversal return, and what is the height of the tree counted in nodes?
Show answer
The in-order traversal returns [1, 3, 6, 8, 10, 14]. The tree has root 8, left child 3 (with children 1 and 6), and right child 10 (with right child 14). The longest path is 8, 3, 1 (or 8, 3, 6, or 8, 10, 14), which has 3 nodes, so the height is 3.
Exercise
A teammate says their tree is a valid BST because every node is larger than its left child and smaller than its right child. Give a small counterexample that passes this check but is not a valid BST, and say how you would detect the problem.
Show answer
Take root 10 with right child 15, and give 15 a left child 5. Locally, 5 is smaller than 15, so the check passes. Globally, 5 sits in the right subtree of 10 but is smaller than 10, which breaks the ordering rule. An in-order traversal gives [10, 5, 15], which is not sorted, so it exposes the error. Passing lower and upper bounds down a recursive check also catches it.