MCS 275 Spring 2023
Emily Dumas
Reminders and announcements:
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.
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.
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:
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.
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.
The three most-often used recursive traversals:
Note: They all visit left child before right child.
node, left, right
Typical use: Make a copy of the tree.
Insert the keys into an empty BST in this order to recreate the original tree.
left, right, node
Typical use: Delete the tree.
If you delete keys in postorder, then you will only ever be removing nodes without children.
left, node, right
Typical use: Turn a BST into a sorted list of keys.
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.
MCS 360 usually covers rebalancing operations.