Lecture 16

Binary Search Trees

Intro & recursive search

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 16: Binary search trees

Reminders and announcements:

  • Project 1 solutions posted
  • Project 2 available
  • Project 2 autograder will be open on Monday

Project 2

Involves solutions to a maze with obstacles (a labyrinth)

Passing obstacles requires equipment, player has mutable inventory

You write several functions that answer questions (solution exists? need this item? etc.)

I provide specs, labyrinth data structure, and sample labyrinths.

Back to dendritic matters...

Sample code

Tree-related examples are in the new directory datastructures in the course sample code repository.

Goals

Learn about search and insert operations on binary search trees.

Implement in Python.

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

Binary search tree

A binary search tree (BST) is a binary tree with keys that can be compared, such that for each node:

  • Left subtree contains only smaller keys
  • Right subtree contains only greater keys

We'll require keys to be distinct. Equal keys can be handled in multiple ways.

Binary tree

Binary tree with keys

BST

NOT a BST

This "just" is a binary tree with keys.

Other tree terms

Last time

Node class represents a node of a binary tree (and the entire subtree with that node as root)

Treevis

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

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
  • Ability to represent an empty tree

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

  • 2023-02-20 Finalization of the 2023 lecture this was based on
  • 2024-02-12 Initial publication