Exam 2 Solutions 1. a. Worst case is when there are 999 internal nodes and only one leaf. Ignoring the leaf and rounding 999 up to 1000, the total amount of memory is 1000*(8 + 2 + 2) = 12000 b. Best case is when there are as many leaves as possible, which is 500. (Why?) So the total amount of memory is 500*(8 + 2 + 2) + 500*8 = 10000 c. Array-based heaps don't use pointers, so it's 1000*8 = 8000 d. Ignoring the root, each node has: data field: 8 bytes size field: 1 byte pointer referencing it: 2 bytes Rounding up the number of non-root nodes to 1000, this gives a total of 11000 e. Ignoring the root, each node has: data field: 8 bytes header pointer: 2 bytes a link contining its array index and next pointer: 6 bytes This gives approximately 16000 total bytes. 2. int howMany(const Key& K) const { return howManyHelpelp(root, K); } b. int howManyHelp(BinNode* subroot, const Key& K) const { if (subroot == NULL) return 0; int i = 0; if (Comp::eq(K, getKey::key(subroot->val()))) i++; return howManyHelp(subroot->left(), K) + howManyHelp(subroot->right(), K) + i; } Or you can make this more efficient by comparing K with the key value in subroot and then recursing left OR right depending on the result of the comparison. 3. a. You can figure out the tree from the code table in part b. There are other solutions to this problem. b. 0 01 1 0001 2 1010 3 00000 4 100 5 110 6 001 7 1011 8 111 9 00001 c. Since 2^3 < 10 < 2^4, the lower bound is 3 and the upper bound is 4. That is, 3 bits is not enough to uniquely encode all 10 digits, but 4 is more than enough. d. Generalizing this idea, letting l be the lower bound and u be the upper, 2^l <= n <=2^u, so l = floor(log_2 n) and u = ceiling(log_2 n). If you just said log_2 + or - 1, that's fine. 4. a. 2^d b. 2^{h-1} - 1 c. 1, 2^{h-1} d. Adding parts b. and c. together, 2^{h-1} <= n <= 2^h - 1 So h-1 <= log_2 n < h, and therefore h is in Theta(log n).