Show contents
Chapter 5 of 7 · 20 min
Binary search trees
By the end of this chapter, you'll be able to
- Describe a binary tree: root, nodes, children, leaves
- State the rule of a binary search tree
- Program insertion and search in a binary search tree
- Traverse a tree to get its values in sorted order
A tree, from top to bottom
A tree is a structure made of nodes. The node at the top is called the root. Each node can have children; a node with no children is a leaf. In a binary tree, each node has at most two children: one on the left, one on the right.
A binary search tree (BST) also follows a rule:
- every value in the left subtree is smaller than the node;
- every value in the right subtree is larger.
To look for a value, you start at the root: smaller, go left; larger, go right. If the tree is balanced, each step rules out about half the nodes: the search costs O(log n).
Programming a BST
Each node is a small object with a value and two links, left and right, which are None as long as there is no child:
class Node:
def __init__(self, value):
self.value = value
self.left = None
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
def contains(root, value):
steps = 0
node = root
while node is not None:
steps += 1
if value == node.value:
return True, steps
node = node.left if value < node.value else node.right
return False, steps
root = None
for v in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, v)
print(contains(root, 60))
print(contains(root, 45))
(True, 3)
(False, 3)
Seven values, and at most three comparisons to know whether a value is there. insert ignores a value that is already present (neither smaller nor larger): the tree holds no duplicates.
Found after visiting 3 nodes out of 7.
Text description of the animation
- The tree: 50 at the root; 30 and 70 below; then 20, 40, 60 and 80.
- We start at the root.
- 60 is larger than 50: the whole left half is ruled out.
- We go down to the right, to 70.
- 60 is smaller than 70.
- We go down to the left, to 60.
- Found after visiting 3 nodes out of 7.
In-order traversal: sorted values
An in-order traversal visits the left subtree first, then the node, then the right subtree. In a BST, it gives the values in ascending order:
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 in_order(root, result):
if root is not None:
in_order(root.left, result)
result.append(root.value)
in_order(root.right, result)
return result
root = None
for name in ["Mei", "Awa", "Tariq", "Kofi", "Lina", "Bintou"]:
root = insert(root, name)
print(in_order(root, []))
['Awa', 'Bintou', 'Kofi', 'Lina', 'Mei', 'Tariq']
Strings compare in alphabetical order: the tree works with any comparable value.
Mini-lab: smallest and largestPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: counting values in a range
A rental app keeps accommodation prices (in CFA francs per night) in a BST. Write count_between(root, low, high) that counts the prices between low and high inclusive, without visiting subtrees that cannot hold useful prices.
prices = [15000, 8000, 25000, 5000, 12000, 20000, 40000]
# count_between(root, 10000, 22000) must return 3
Hint 1
low, its whole left subtree is too: only the right subtree can hold useful prices.Hint 2
high, only the left side matters. Otherwise, count the node and look on both sides.Show the solution and common mistakes
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 count_between(root, low, high):
if root is None:
return 0
if root.value < low:
return count_between(root.right, low, high)
if root.value > high:
return count_between(root.left, low, high)
return 1 + count_between(root.left, low, high) + count_between(root.right, low, high)
root = None
for p in [15000, 8000, 25000, 5000, 12000, 20000, 40000]:
root = insert(root, p)
print(count_between(root, 10000, 22000))
3
The prices 12,000, 15,000 and 20,000 are in the range. The branches holding 5,000 and 40,000 are never visited.
Common mistakes:
- Going through the whole tree and testing each node: the result is correct, but you lose the point of the BST.
- Writing
<instead of<=for the bounds, or the other way round: reread the statement ("inclusive") and test with a bound equal to an existing price.
Summary
- 1A binary tree is made of nodes with at most two children; the node at the top is the root.
- 2In a binary search tree, everything on the left is smaller and everything on the right is larger.
- 3If the tree is balanced, searching and inserting cost O(log n).
- 4In-order traversal (left, node, right) gives the values in sorted order.
- 5Data inserted in order unbalances the tree: searching becomes O(n) again.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.