CS106X – Programming Abstractions Dr. Cynthia Bailey Lee 2 Today’s Topics 1. TreeMap 2. Tree traversals Abstract syntax tree (calculator) Hashmap (if we have time) A quick look inside hash functions Tree traversals What does this print? void traverse(Node *node) { if (node != NULL) { cout << node->key << " "; traverse(node->left); traverse(node->right); } } A. B. C. D. E. ABCDEF ABDECF DBEFCA DEBFCA Other/none/more A B D C E F What does this print? void traverse(Node *node) { if (node != NULL) { traverse(node->left); cout << node->key << " "; traverse(node->right); } } A. B. C. D. E. ABCDEF ABDECF DBEFCA DEBFCA Other/none/more A B D C E F We can play the same game with non-alpha characters as keys: What does this print? void traverse(Node *node) { if (node != NULL) { traverse(node->left); traverse(node->right); cout << node->key << " "; } } A. B. C. D. E. *+/3482 *+34/2 3+4*8/2 34+82/* Other/none/more * + 3 / 4 8 2 Remember our old friend: How can we get this to print our ABCs in order? void traverse(Node *node) { if (node != NULL) { cout << node->key << " "; traverse(node->left); traverse(node->right); } D } A. B. C. D. A B C E F You can’t—we already tried moving the cout to all 3 possible places. You can but you use a stack instead of recursion. You can but you use a queue instead of recursion. Other/none/more That prints the ABC nodes in order, but notice that our ABC tree isn’t a BST. How do we print BST nodes in order? void traverse(Node *node) { if (node != NULL) { traverse(node->left); traverse(node->right); } } A. B. C. D. E. Use the BFS (queue instead of recursion). Use the DFS and put cout first. Use the DFS and put cout between. Use the DFS and put cout last. Other/none/more Hashmap A peek inside the Stanford library implementation Recall this slide from Monday. We will compare what we said here with what is done in Stanford library: One really simple approach Hash table (array) size is some prime number Keep the array size big enough that at most 70% of the slots are filled Somehow convert your data to an int and then int hash(int input){ return input % size; } Can we still get super unlucky? YES Hashmap analysis of O(1) is “average case” For a really nicely designed hash: 99.9% of the time