Lecture 17

Binary Search Trees

Recursive Insert & BST Application

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 17: BST and tree traversals

Reminders and announcements:

  • Project 2 available!
  • Project 2 autograder opens Monday 😬
  • Homework 6 available.
  • Also available:
    • Worksheet 6 solutions
    • Homework 5 solutions
    • Homework 4 grades

BST methods

Let's add insert to trees.py:

  • Search for key k (that is not present)
  • At the moment we determine it is missing, we've found a place it can be added.
  • Create a new BST object and make it the appropriate child.

treeutil

I added a module to the datastructures directory of the sample code repository which can generate random trees. You'll use it in lab this week.

Think about

How would you make purely iterative versions of insert and search?

e.g. a function completely separate from the class called like bst_insert(root,new_key)

Other BST tasks

  • 🟡 Allow empty tree (root has key None)
  • 🟡 Verbose mode for insert/search
  • ❌ Node deletion
  • ❌ Balancing (rearrange so there are lots of two-child nodes)

IntegerSet

As a sample application of BST, we can make a class that stores a set of integers, supporting membership testing and adding new elements.

Compare alternatives:

  • Unsorted list - fast to insert, but slow membership test
  • Sorted list - fast membership test, slow insert
  • Python's set - fast everything
  • Hash table - fast everything

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

  • 2023-02-23 Finalization of the 2023 lecture this was based on
  • 2024-02-16 Initial publication