CPSC 221

Level Order, and Dictionaries

Today

Announcements

  • Examlet 4 is open until Sunday
  • PEX5 (trees and traversals) is up


Where we’re going

  • Traversal running time
  • Level-order traversal (or how to do PA2)
  • ADT Dictionary

Traversal — running time

\(T(n)\): running time of a traversal on a tree with \(n\) nodes.

\(T(0) = 1\)

\(T(n) = T(n_L) + T(n_R) + 1,\; n > 0.\)

Thm: \(T(n) = 2n + 1,\; n \ge 0.\)

template<class T>
void tree<T>::preOrder(Node * croot) {
    if (croot != nullptr) {
        cout << croot->data;
        preOrder(croot->left);
        preOrder(croot->right);
    }
}
10 12 15 3 9 7 20 30 8

Traversals: something totally different…

+ - / b c * d e

    a)

    b)

        i.

        ii.



template<class T>
void tree<T>::levelOrder(Node * croot) {










}

Traversals summary

+ - / b c * d e
  1. We’ve studied 4 but…


  1. Running time

ADT Dictionary

Suppose we have the following data…

locker # Name
103 Jay Hathaway
92 Linda Stencel
330 Bonnie Cook
46 Rick Brown
124 Kim Petersen
… …

…and we want to be able to retrieve a name, given a locker number.

More examples of key/value pairs:

  • CWL → Advising record
  • Course number → Schedule info
  • Color → PNG
  • Vertex → Set of incident edges
  • Flight number → Arrival information
  • URL → html page


A dictionary is a structure supporting:

void insert(kType & k, dType & d)
void remove(kType & k)
dType find(kType & k)

ADT Dictionary: implementation options…

insert find (find +) remove
linked list \(\Theta(1)\) \(\Theta(n)\) \(\Theta(n) + \Theta(1)\)
unsorted array \(\Theta(1)\) \(\Theta(n)\) \(\Theta(n) + \Theta(1)\)
sorted array \(\Theta(\log n) + \Theta(n)\) \(\Theta(\log n)\) \(\Theta(\log n) + \Theta(n)\)
Binary Tree?