Lecture 17

Binary Search Trees

MCS 275 Spring 2023
Emily Dumas

Lecture 17: Binary search trees

Reminders and announcements:

  • Project 2 due at 6pm on Friday
  • Project 1 solutions posted

Sample code

Tree-related examples will go 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 (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_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

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 Last year's lecture on this topic finalized
  • 2023-02-20 Updated for 2023