Lecture 20

Binary Search Trees

MCS 275 Spring 2022
Emily Dumas

Lecture 20: Binary search trees

Course bulletins:

  • Project 2 due 6pm today

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 subclass of Node to represent a BST.

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

Given a key, add a node to the tree with that key, maintaining the BST property.

IntegerSet

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

Implementation Hiding

IntegerSet has many possible implementations (e.g. a list, a tree, ...), and a user of the class doesn't need to know about which one it uses.

References

Revision history

  • 2022-02-24 Initial publication