Kodewick
Start learning →
Binary search trees25 / 52

Binary search trees

Lesson 25 of 52 · Part 5 · Trees and heaps · about 18 minutes

A binary search tree keeps smaller values on the left of every node and larger ones on the right, so search, insert and delete take as many steps as the tree is tall, an inorder traversal comes out sorted, and sorted input turns it into a line.

A list holds a million user IDs, and you keep asking "is this ID there?", adding new ones, removing old ones, and now and then listing them in order. An unsorted list scans a million items per lookup; a sorted list allows binary search, but each insert shifts everything after it. A binary search tree (BST) wants both: when its shape is balanced, search, insert and delete take only about 20 steps, and one inorder traversal lists everything from smallest to largest. The catch is that it does not keep itself balanced: insert sorted numbers one by one and it becomes a line, taking a million steps each time.

Smaller on the left, larger on the right

A binary search tree has a single rule: for every node, all values in its left subtree are smaller and all values in its right subtree are larger. Note that it is the whole subtree, not just the two children.

To search for a number, start at the root and compare: if equal, you found it; if smaller than the current node, the answer can only be in the left subtree; if larger, only in the right. Each comparison goes one level down, and the whole subtree on the other side never needs a look.

8
3
1
6
4
7
10
14

Searching for 7 in a binary search tree: go left when smaller, right when larger; 4 comparisons, each throwing away a whole subtree on the other side
Choose one

In this stage's tree (8 has left child 3 and right child 10; 3 has children 1 and 6; 6 has children 4 and 7; 10 has only a right child, 14), how many comparisons does a search for 5 make before it knows 5 isn't there?

Choose one

5's left child is 3, 3's right child is 6, and there are no other nodes. Is this a binary search tree?

Exercise 1

Is it a binary search tree?

Complete is_bst(node, lo, hi): every value in the subtree must lie strictly between lo and hi. Going left, the upper bound becomes the current value; going right, the lower bound does.

It should print
True False False True
exercise1.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def is_bst(node, lo=float("-inf"), hi=float("inf")):8    # an empty tree is one; a value outside (lo, hi) is not; then check both sides9    return True10 11good = TreeNode(5, TreeNode(3, TreeNode(1), TreeNode(4)), TreeNode(8))12bad = TreeNode(5, TreeNode(3, TreeNode(1), TreeNode(6)), TreeNode(8))13same = TreeNode(2, TreeNode(2))14print(is_bst(good), is_bst(bad), is_bst(same), is_bst(None))
Output
Press Run or Ctrl+Enter

Insert: walk down to an empty spot

Insert follows the same path as search: start at the root, go left when the new value is smaller and right when it is bigger, compare all the way down, and the place where you reach None is where the new value belongs. The new node is always a leaf, and none of the existing nodes moves.

8
3
1
6
4
7
10
14

Inserting 13: follow the search path, and put it down at the empty place. None of the existing nodes moves
main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert(node, x):8    if node is None:9        return TreeNode(x)                 # reached an empty place: put it here10    if x < node.val:11        node.left = insert(node.left, x)12    elif x > node.val:13        node.right = insert(node.right, x)14    return node                            # equal: already there, not added twice15 16def search(node, x):17    steps = 018    while node:19        steps += 120        if x == node.val:21            return True, steps22        node = node.left if x < node.val else node.right23    return False, steps24 25def inorder(node):26    if node:27        yield from inorder(node.left)28        yield node.val29        yield from inorder(node.right)30 31root = None32for x in [8, 3, 10, 1, 6, 14, 4, 7]:33    root = insert(root, x)34print(list(inorder(root)))35print(search(root, 7), search(root, 5), search(root, 13))36root = insert(root, 13)37print(search(root, 13))
Output
[1, 3, 4, 6, 7, 8, 10, 14]
(True, 4) (False, 4) (False, 3)
(True, 4)

insert is shortest written recursively: the line node.left = insert(node.left, x) attaches the new node when the left is None, and attaches the same subtree back when it isn't. Search is a loop, like binary search, just going down one path.

Look at the first line printed: inorder is "left, root, right", the left is all smaller than the root and the right all larger, so a binary search tree's inorder traversal is always sorted. It is also the simplest way to check whether a tree is a BST.

Guess the outputA wrong guess is fine

Insert 5 2 8 2 9 1 in turn (2 appears twice). What does the inorder traversal print?

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert(node, x):8    if node is None:9        return TreeNode(x)10    if x < node.val:11        node.left = insert(node.left, x)12    elif x > node.val:13        node.right = insert(node.right, x)14    return node15 16def inorder(node):17    return inorder(node.left) + [node.val] + inorder(node.right) if node else []18 19root = None20for x in [5, 2, 8, 2, 9, 1]:21    root = insert(root, x)22print(inorder(root))
Choose one

Insert 50 30 70 20 40 60 80 35 in that order. Whose child is 35, and which side?

Delete: three cases

To delete, first find the node, then look at how many children it has:

  1. A leaf: just take it away; the parent's link becomes None.
  2. One child: the child moves up and is attached to the parent. Its whole subtree is on the same side as the deleted node, so the rule still holds.
  3. Two children: it can't just be taken away, since its two subtrees would have nowhere to go. Instead, find a value to replace it: the smallest in its right subtree, called the in-order successor (the one right after it in inorder). It is larger than everything on the left and smaller than everything else on the right, so it fits exactly here. Copy its value over, then delete the successor from the right subtree; the successor never has a left child (or that child would be smaller), so deleting it is case 1 or 2.
8
3
1
6
4
7
10
14

Deleting 7 (a leaf), then 10 (one child), then 3 (two children: replaced by 4, the smallest in its right subtree)
main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert(node, x):8    if node is None:9        return TreeNode(x)10    if x < node.val:11        node.left = insert(node.left, x)12    elif x > node.val:13        node.right = insert(node.right, x)14    return node15 16def delete(node, x):17    if node is None:18        return None                        # not found: do nothing19    if x < node.val:20        node.left = delete(node.left, x)21    elif x > node.val:22        node.right = delete(node.right, x)23    else:24        if node.left is None:              # a leaf, or only a right child25            return node.right26        if node.right is None:             # only a left child27            return node.left28        succ = node.right                  # two children: find the in-order successor29        while succ.left:30            succ = succ.left31        node.val = succ.val32        node.right = delete(node.right, succ.val)33    return node34 35def pre(node):36    return [node.val] + pre(node.left) + pre(node.right) if node else []37 38def ino(node):39    return ino(node.left) + [node.val] + ino(node.right) if node else []40 41root = None42for x in [8, 3, 10, 1, 6, 14, 4, 7]:43    root = insert(root, x)44print("start", pre(root))45for x in [7, 10, 3, 99]:46    root = delete(root, x)47    print("delete", x, pre(root), ino(root))
Output
start [8, 3, 1, 6, 4, 7, 10, 14]
delete 7 [8, 3, 1, 6, 4, 10, 14] [1, 3, 4, 6, 8, 10, 14]
delete 10 [8, 3, 1, 6, 4, 14] [1, 3, 4, 6, 8, 14]
delete 3 [8, 4, 1, 6, 14] [1, 4, 6, 8, 14]
delete 99 [8, 4, 1, 6, 14] [1, 4, 6, 8, 14]

Like insert, delete returns "the root of this subtree after the delete", and the parent catches it with node.left = delete(...). Cases 1 and 2 are folded into two lines: if the left child is None, return the right child (a leaf's right child is None too, so that returns None, just right).

Choose one

In the tree at the start of this stage (root 8, right subtree 10 with right child 14), delete the root 8. With this stage's method, what is the new root?

Fill inTap one to fill a blank; tap a blank to take it back

Pick one for both blanks so that the loop finds the inorder successor and the inorder stays in increasing order after deleting the root 8.

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert(node, x):8    if node is None:9        return TreeNode(x)10    if x < node.val:11        node.left = insert(node.left, x)12    elif x > node.val:13        node.right = insert(node.right, x)14    return node15 16def delete(node, x):17    if node is None:18        return None19    if x < node.val:20        node.left = delete(node.left, x)21    elif x > node.val:22        node.right = delete(node.right, x)23    else:24        if node.left is None:25            return node.right26        if node.right is None:27            return node.left28        succ = node.right29        while succ.:30            succ = succ.31        node.val = succ.val32        node.right = delete(node.right, succ.val)33    return node34 35def ino(node):36    return ino(node.left) + [node.val] + ino(node.right) if node else []37 38root = None39for x in [8, 3, 10, 9, 14]:40    root = insert(root, x)41root = delete(root, 8)42print(root.val, ino(root))

Sorted input: a line

Search, insert and delete all walk one path down from the root, so they take as many steps as the tree's height h. How big h gets depends entirely on the order of insertion. Insert 1 to 127 in order:

1

Inserting in the order 1 2 3 4 5: each new number is larger than everything already there, so it always goes right, and the tree becomes a line

Count it for 127 numbers in two insertion orders:

main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert_count(root, x):                 # returns (root, comparisons made)8    if root is None:9        return TreeNode(x), 010    node, cmps = root, 011    while True:12        cmps += 113        if x < node.val:14            if node.left is None:15                node.left = TreeNode(x)16                return root, cmps17            node = node.left18        else:19            if node.right is None:20                node.right = TreeNode(x)21                return root, cmps22            node = node.right23 24def height(node):25    return 1 + max(height(node.left), height(node.right)) if node else 026 27def middle_first(lo, hi, out):             # the middle first, then the middles of the halves…28    if lo <= hi:29        mid = (lo + hi) // 230        out.append(mid)31        middle_first(lo, mid - 1, out)32        middle_first(mid + 1, hi, out)33    return out34 35for name, order in [("in order 1..127", list(range(1, 128))),36                    ("middle first", middle_first(1, 127, []))]:37    root, total = None, 038    for x in order:39        root, c = insert_count(root, x)40        total += c41    print(name + ": comparisons", total, "height", height(root))
Output
in order 1..127: comparisons 8001 height 127
middle first: comparisons 642 height 7

The same 127 numbers: in order, 8001 comparisons (0 + 1 + … + 126) and height 127; in another order, only 642 comparisons and height 7. For n numbers one is O(n²) and the other O(n log n). Real data is often sorted or nearly so (auto-increment IDs, timestamps), which is why the trees actually used are balanced trees: AVL and red-black trees "rotate" on insert and delete to keep the height O(log n). Chapter 6 covers AVL.

OperationBalanced tree (h ≈ log n)A line (h = n)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
Inorder traversal (list in order)O(n)O(n)
Min / max (left / right all the way)O(log n)O(n)

In interviews: the most common mistake in "validate a binary search tree" is comparing only parent and child: 5 → left 3 → right 6 passes 3 < 5 and 6 > 3, yet 6 sits in 5's left subtree, which is illegal. Either pass lower and upper bounds down, or walk inorder and check that it strictly increases. When giving the cost, always say "O(h): O(log n) when balanced, O(n) at worst".

Choose one

Insert 1, 2, …, n in that order into an empty BST. How many comparisons does it take in total?

Guess the outputA wrong guess is fine

The same 7 numbers in two insertion orders. Print the heights of the two trees:

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert(node, x):8    if node is None:9        return TreeNode(x)10    if x < node.val:11        node.left = insert(node.left, x)12    elif x > node.val:13        node.right = insert(node.right, x)14    return node15 16def height(node):17    return 1 + max(height(node.left), height(node.right)) if node else 018 19hs = []20for order in [[4, 2, 6, 1, 3, 5, 7], [1, 2, 3, 4, 5, 6, 7]]:21    root = None22    for x in order:23        root = insert(root, x)24    hs.append(height(root))25print(*hs)

How you write it at work

The standard library has no binary search tree, and no balanced tree either. Everyday needs split up like this:

  • Only "is it there?" or looking up by key: set and dict, O(1) on average, faster than any tree.
  • Order and range queries ("how many scores between 80 and 90?"): a sorted list plus bisect. Search is O(log n); insort has to shift items, O(n), but it shifts one block of memory, which is fast up to tens of thousands of items.
  • Many inserts and deletes on big data: SortedList from the third-party sortedcontainers, or a database index (a B+ tree).
main.py
1import bisect2 3scores = []4for s in [72, 95, 88, 61, 90, 85, 79]:5    bisect.insort(scores, s)               # still sorted after each insert6print(scores)7 8lo = bisect.bisect_left(scores, 80)        # the first position with a score >= 809hi = bisect.bisect_right(scores, 90)       # the first position with a score > 9010print("80 to 90:", scores[lo:hi], hi - lo, "scores")11 12i = bisect.bisect_right(scores, 87)        # the largest not above 87 (the floor)13print("largest score not above 87:", scores[i - 1])
Output
[61, 72, 79, 85, 88, 90, 95]
80 to 90: [85, 88, 90] 3 scores
largest score not above 87: 85

bisect walks the same "compare once, throw away half" path a BST search does, only on a sorted list. Binary search in chapter 6 looks at its boundaries closely.

Choose one

scores = [61, 72, 79, 85, 88, 90, 95]. What is bisect.bisect_left(scores, 85)?

Exercise 2

Sum in a range

Complete range_sum(node, lo, hi): return the sum of all values in the BST between lo and hi inclusive. Use smaller-left, larger-right: if the current value is below lo, the left subtree needs no look at all. The program also prints how many nodes were visited.

It should print
40 7
exercise2.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert(node, x):8    if node is None:9        return TreeNode(x)10    if x < node.val:11        node.left = insert(node.left, x)12    elif x > node.val:13        node.right = insert(node.right, x)14    return node15 16visits = 017 18def range_sum(node, lo, hi):19    global visits20    if node is None:21        return 022    visits += 123    # below lo: only the right; above hi: only the left; in the range: itself plus both sides24    return 025 26root = None27for x in [10, 5, 15, 3, 7, 18, 1, 4, 6, 8]:28    root = insert(root, x)29print(range_sum(root, 7, 15), visits)
Output
Press Run or Ctrl+Enter

Summary

Take-away

Binary search trees: smaller left, larger right

  • Search and insert walk one path down, throwing away one side each step; a new node is always a leaf
  • Delete: a leaf just goes; one child moves up; two children are replaced by the in-order successor (the smallest on the right)
  • Inorder traversal is always sorted
  • Cost O(h): log n when balanced; sorted input degenerates into a line, O(n)
  • At work: dict / set for "is it there", a sorted list + bisect for order and ranges
1def insert(node, x):2    if node is None: return TreeNode(x)3    if x < node.val: node.left = insert(node.left, x)4    elif x > node.val: node.right = insert(node.right, x)5    return node