Tree traversal preorder, postorder: applies to any kind of tree inorder: applies only to binary trees void BST::Traverse (BinaryNode *node) { if (node == NULL) // return an appropriate value return; else // PREORDER: compute/use node here Traverse (node->left); // INORDER: compute/use node here Traverse (node->right); // POSTORDER: compute/use node here } Oct 31, 2001 CSE 373, Autumn 2001
Tree traversal, example int NumLeaves (BNode<Comp> *tree) { if (tree == NULL) return 0; else int sum = 0; sum = NumLeaves(tree->left) + NumLeaves(tree->right); if ((tree->left == NULL) && (tree->right == NULL)) sum += 1; } return sum; Oct 31, 2001 CSE 373, Autumn 2001
Tree traversal, example 2 D B F A C E G preorder: ?? inorder: ?? postorder: ?? level order (use a queue): ?? Oct 31, 2001 CSE 373, Autumn 2001
Open Addressing Examine cells in the order h0(x), h1(x), h2(x), … where hi(k)=(hash(k) + f(i)) mod TableSize Linear Probing f(i) = i After searching spot hash(k) in the array, look in hash(k) + 1, hash(k) + 2, etc. example: insert 38, 19, 8, 109, 10 Oct 31, 2001 CSE 373, Autumn 2001
Linear Probing example 8 1 109 2 10 3 4 5 6 7 38 9 19 38 19 8 109 10 primary clustering Oct 31, 2001 CSE 373, Autumn 2001
Quadratic Probing f(i) = i2 After searching spot hash(k), look in the 1st, 4th, 9th, etc. spots after hash(k). Less likely to encounter primary clustering. … n-1 Oct 31, 2001 CSE 373, Autumn 2001
Double Hashing f(i) = i · hash2(x) Items that hash to the same location with hash(x) won’t have the same probe for hash2(x). Oct 31, 2001 CSE 373, Autumn 2001
Analysis of find Defn: The load, , of a hash table is the ratio: no. of elements table size Separate chaining unsuccessful: (avg. length of a list at hash(k)) successful: 1 + (/2) (one node, plus half the avg. length of a list (not including the item)). Oct 31, 2001 CSE 373, Autumn 2001
Open addressing Linear probing unsuccessful: successful: (Analysis from Knuth) Oct 31, 2001 CSE 373, Autumn 2001
Random Collision Resolution Model Goal: see how collisions occur under ideal conditions. On an insertion, each probe is independent of previous probes. On a successful find, the exact probe sequence used in insertion is used. unsuccessful: 1/(1 - ) (1- ) fraction of the cells are empty. successful: (ln means loge ) Oct 31, 2001 CSE 373, Autumn 2001
Comparison Double hashing – performance approximated by the random collision resolution model. linear probing random collision unsucc. successful 0.1 1.1 0.3 1.5 1.4 1.2 0.5 2.5 2.0 0.7 6.1 3.3 2.2 1.7 0.9 50.5 10.0 5.5 2.6 Oct 31, 2001 CSE 373, Autumn 2001
Rehashing Idea: When the table gets too full, create a bigger table and hash all the items from the original table into the new table. When to rehash? half full ( = 0.5) when an insertion fails some other threshold Cost of rehashing Oct 31, 2001 CSE 373, Autumn 2001