Lecture 20

Binary Search Trees

MCS 275 Spring 2021
Emily Dumas

Lecture 20: Binary search trees

Course bulletins:

  • Project 2 due 6pm CST today.
  • Starting on worksheet 8, problem 1 will have special instructions.
    • Tue discussion: Problem 1 will be presented as an example.
    • Thu discussion: Please do problem 1 ahead of time.

Sample code

I've created a new directory trees in the course sample code repository.

Live coding examples from the next couple of lectures will be added there.

Goal

Learn about search and insert operations on binary search trees.

Explore an application to a fast data structure for storing a set of integers.

Binary search tree (BST)

A binary tree in which:

  • Nodes have keys that can be compared
  • The key of a node is greater than or equal to any key in its left subtree.
  • The key of a node is less than or equal to any key in its right subtree.

Binary tree

BST

NOT a BST

This "just" is a binary tree with keys.

Tree terms

Coding

Let's build a class to represent nodes of a binary tree that also store keys.

Treevis

I provide a module treevis in the sample code repository that can "pretty print" a tree with the function treeprint(root).

Challenge: Read the source of treevis and figure out how it works!

From tree to BST

Now let's build a class that builds and manages a BST made of Node objects.

Desired features:

  • Insert nodes (maintaining BST property)
  • Search for nodes by key

Search

Given x, find and return a node with key x. Return None if no such node exists.

Insert

Take a Node object and add it to the tree in a place that maintains the BST property.

The node must have its key set, but not its parent and children. Insert will handle those.

IntegerSet

Let's use this to build a class to store a collection of integers that supports fast insertion and membership testing.

Implementation Hiding

To use BST, you need to know about and work with Node objects.

In contrast, IntegerSet has an interface based directly on the values to be stored. It hides the fact that its implementation uses a BST.

References

Revision history

  • 2021-02-26 Fix incorrect integer comparison in one figure; add link to sample code
  • 2021-02-25 Initial publication