Lecture 18

BST and tree traversals

MCS 275 Spring 2023
Emily Dumas

Lecture 18: BST and tree traversals

Reminders and announcements:

  • Project 2 due today.
  • Homework 7 available.
  • Project 1 will be graded by Monday.
    • It's only the manual review you're waiting on; the autograder results account for most of the project grade.

Updated BST class

I put an implementation of binary search tree (as class BST) in trees.py.

Also modified so BST() is considered a valid, empty tree. (That is, None as a key is treated specially.)

BST.search also supports a verbose mode.

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.

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

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.

Walking a tree

Back to discussing binary trees (not necessarily BST).

For some purposes we need to visit every node in a tree and perform some action on them.

To do this is to traverse or walk the tree.

Named traversals

The three most-often used recursive traversals:

  • preorder - Node, left subtree, then right subtree.
  • postorder - Left subtree, right subtree, then node.
  • inorder - Left subtree, node, then right subtree.

Note: They all visit left child before right child.

Preorder traversal

node, left, right

Preorder traversal

Typical use: Make a copy of the tree.

Insert the keys into an empty BST in this order to recreate the original tree.

Postorder traversal

left, right, node

Postorder traversal

Typical use: Delete the tree.

If you delete keys in postorder, then you will only ever be removing nodes without children.

Inorder traversal

left, node, right

Inorder traversal

Typical use: Turn a BST into a sorted list of keys.

Uniquely describing a tree

Many different binary trees can have the same inorder traversal.

Many different binary trees can have the same preorder traversal.

And yet:

Theorem: A binary tree T is uniquely determined by its inorder and preorder traversals.

Last words on binary trees

  • BSTs make a lot of data accessible in a few "hops" from the root.
  • They are a good choice for mutable data structures involving search operations.
  • Deletion of a node is an important feature we didn't implement. (Take MCS 360!)
  • Unbalanced trees are less efficient.

MCS 360 usually covers rebalancing operations.

References

Revision history

  • 2022-02-28 Last year's lecture on this topic finalized
  • 2023-02-23 Updated for 2023