CPSC 221

Binary Search Trees

Today

Announcements

  • PA2 is due next Monday, 11/02
  • Examlet 5 is this week — book your seat on PrairieTest


Today:

  • An ordered tree
  • BST find and insert
  • BST remove: introduction
  • Efficiency

Where is 25?

A dictionary stores keys so we can find, insert, and remove them.


Where would you look for 25?

Where would you put 37?

42 17 8 99 3 56

What do you notice?

Binary search tree

38 13 51 10 25 40 84 12 37 66 89 95

A Binary Search Tree (BST) is a binary tree, T, such that:

  • ____________, OR

  • T = {r, TL, TR} and

    x ∈ TL → ______________

    x ∈ TR → ______________

and

Dictionary ADT (BST implementation)

38 13 51 25 40 84 12 89 95
  • insert
  • remove
  • find
  • traverse
template<class K, class D>
class Dictionary {
public:   // ctors etc
    ...
private:
    struct Node {
        D data;
        K key;
        Node * left;
        Node * right;
    };
    Node * root;
    ...
};

Binary search tree — insert

38 13 51 10 25 40 84 12 37 66 89 95

What if key == croot->key?


Running time:

template<class K>
void insert(Node * croot, const K & key) {

    if (croot == nullptr)
        croot = new Node(key);

    else if (key < croot->key)
        insert(croot->left);

    else if (key > croot->key)
        insert(croot->right);
}

Your Turn

Pick A or B at random. On paper, insert those keys in that order into an empty BST.

A

4, 2, 6, 1, 3, 5, 7

B

1, 2, 3, 4, 5, 6, 7


Then find someone who picked the other list, and compare.

  • Same keys, same insert code. What’s different?
  • Which tree would you rather run find(7) on?

Binary search tree — find

38 13 51 10 25 40 84 12 37 66 89 95

Running time:

template<class K>
Node *& find_(K & key, Node *& r) {

    if (r == nullptr)


    else if (r->key == key)


    else if


    else

}

What happens when we remove?

Binary search tree — remove

T.remove(37);

38 13 51 10 25 84 12 37 66 89 95

T.remove(51);

38 13 51 10 25 84 12 37 66 89 95

Binary search tree — remove

38 13 51 10 25 40 84 12 37 66 89 95
void BST<K>::remove(Node *& croot, const K & k) {
    if (croot != nullptr) {
        if (croot->key == key)
            doRemoval(cRoot);
        else if (k < croot->key)
            remove(cRoot->left, k);
        else
            remove(cRoot->right, k);
    }
}
void BST<K>::doRemoval(Node * & cRoot) {
    if ((croot->left != nullptr) && ((croot->right != nullptr) {
        _____ChildRemove(cRoot);
    else
        _____ChildRemove(cRoot);
}

Binary search tree — remove

38 13 51 10 25 40 84 12 37 66 89 95
void BST<K>::zeroOneChildRemove(Node * & cRoot) {
    Node * temp = cRoot;
    if (cRoot->left == nullptr) cRoot = cRoot->right;
    else cRoot = cRoot->left;
    delete temp;
}

Binary search tree — summary

38 13 51 10 25 40 84 12 37 66 89 95

Running time of Dictionary functions?

Which traversal sorts the keys?

What’s left?