Exam II with Solutions for Data Structures | CS 225, Exams of Data Structures and Algorithms

Material Type: Exam; Class: Data Structures; Subject: Computer Science; University: University of Illinois - Urbana-Champaign; Term: Spring 2008;

Typology: Exams

Pre 2010

Uploaded on 03/16/2009

koofers-user-uki
koofers-user-uki 🇺🇸

10 documents

1 / 18

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
University of Illinois at Urbana-Champaign
Department of Computer Science
Second Examination
CS 225 Data Structures and Software Principles
Spring 2008
7p-9p, Tuesday, March 25
Name:
NetID:
Lab Section (Day/Time):
This is a closed book and closed notes exam. No electronic aids are allowed, either.
You should have 5 problems total on 20 pages. The last two sheets are scratch paper; you
may detach them while taking the exam, but must turn them in with the exam when you
leave.
Unless otherwise stated in a problem, assume the best possible design of a particular imple-
mentation is being used.
Unless the problem specifically says otherwise, (1) assume the code compiles, and thus any
compiler error is an exam typo (though hopefully there are not any typos), and (2) assume
you are NOT allowed to write any helper methods to help solve the problem, nor are you
allowed to use additional arrays, lists, or other collection data structures unless we have said
you can.
Please put your name at the top of each page.
Problem Points Score Grader
1 20
2 30
3 10
4 20
5 20
Total 100
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download Exam II with Solutions for Data Structures | CS 225 and more Exams Data Structures and Algorithms in PDF only on Docsity!

University of Illinois at Urbana-Champaign

Department of Computer Science

Second Examination

CS 225 Data Structures and Software Principles

Spring 2008

7p-9p, Tuesday, March 25

Name:

NetID:

Lab Section (Day/Time):

  • This is a closed book and closed notes exam. No electronic aids are allowed, either.
  • You should have 5 problems total on 20 pages. The last two sheets are scratch paper; you may detach them while taking the exam, but must turn them in with the exam when you leave.
  • Unless otherwise stated in a problem, assume the best possible design of a particular imple- mentation is being used.
  • Unless the problem specifically says otherwise, (1) assume the code compiles, and thus any compiler error is an exam typo (though hopefully there are not any typos), and (2) assume you are NOT allowed to write any helper methods to help solve the problem, nor are you allowed to use additional arrays, lists, or other collection data structures unless we have said you can.
  • Please put your name at the top of each page.

Problem Points Score Grader

Total 100

  1. [Choices, Choices! – 20 points].

MC1 (2.5pts)

Which of the following is true about trees?

(a) A perfect binary tree is a binary tree in which every node has exactly zero or two children. (b) A binary tree of height h can have at most 2h + 1 nodes. (c) For a tree with more than 3 nodes, inorder and postorder traversals can’t be the same. (d) If you are given a tree’s preorder, inorder, and postorder traversals you can construct the tree. (e) None of these is true.

MC2 (2.5pts)

If values 1, 2, and 3 are added to a binary search tree in all possible orderings, how many unique trees can be made?

(a) 4 (b) 5 (c) 6 (d) 8 (e) none of the above

MC5 (2.5pts)

In an n node AVL tree, what is the worst-case running time for a removal?

(a) O(n) to find the node to be removed and O(1) to rebalance the tree after removing it. (b) O(log n) to find the node to be removed and O(1) to rebalance the tree after removing it. (c) O(log n) to find the node to be removed and O(n) to rebalance the tree after removing it. (d) O(n) to find the node to be removed and O(log n) to rebalance the tree after removing it. (e) O(log n) to find the node to be removed and O(log n) to rebalance the tree after removing it.

MC6 (2.5pts)

In the following binary tree, which nodes are not height-balanced?

(a) B, C, and D (b) B and C (c) D and E (d) A, B, and E (e) All the nodes are height-balanced.

MC7 (2.5)

Our implementation of a level order traversal of a binary tree used a variable of type queue (a queue object) to keep track of the order in which the nodes are processed. What kind of traversal results if the queue variable is replaced by a stack, and the children of a node are placed on the stack right child first, and then left?

(a) preorder traversal (b) inorder traversal (c) postorder traversal (d) level order traversal (e) the result is not a traversal

MC8 (2.5)

In a B-Tree of order m containing n items, what are the minimum and maximum number of children that a non-root internal node can have?

(a) A minimum of 1 and a maximum of m (b) A minimum of d(m/2)e and maximum of m − 1 (c) A minimum of d(m/2)e and a maximum of m (d) A minimum of m and a maximum of log n (e) None of the above.

Inductive Step: Let m be the least number of nodes in a full ternary tree of height h + 1. Given that this property holds for a full ternary tree of height h with n nodes (n ≥ 3 h + 1), show it holds for height h + 1 (m ≥ 3(h + 1) + 1).

Let the Inductive Hypothesis (IH) be n ≥ 3 h + 1 for a full ternary tree of height h and let n be the number of nodes it contains.

Let T be an arbitrary full ternary tree of height h with the least number of nodes. By the IH, we know that the least number of nodes for a full ternary tree of height h is n. So T contains n nodes. Let i be an arbitrary leaf node of T at the greatest depth. To construct a ternary tree of height h + 1 with the least number of nodes, we can increase the height of T by 1 by adding a new child node to i. However, in order to construct a full ternary tree, T ′, of height h + 1 with the least number of nodes, we can increase the height of T by 1 by letting three new single nodes be the children of i. Therefore, T ′^ contains n + 3 nodes. Since T ′^ is an arbitrary full ternary tree of height h + 1 with the least number of nodes, we know m = n + 3 by the definition of m.

By the IH, n ≥ 3 h + 1 By algebra, n + 3 ≥ 3 h + 1 + 3 By arithmetic, n + 3 ≥ 3(h + 1) + 1 By substitution, m ≥ 3(h + 1) + 1

Therefore, we have shown by induction that n ≥ 3 h + 1 for all full ternary trees of height h with n nodes.

Rubric: 1pt - proving the base case 1pt - defining the IH 1pt - explaining that why three nodes are added 1pt - properly using the IH 1pt - proving the inductive step -1pt - using undefined variables

Note: The solution given here is much more formal than we are expecting your poof to be. However, we are expecting some informal valid equivalent.

(b) A ternary search tree (TST) is used to store a dictionary of English words as shown in the following example. Each node contains a single character. Each path from the root to a node with no middle child corresponds to a word. Notice, though, that the exact sequence of letters in such a path do not correspond exactly to the letters in a word. Rather, letters in the path that are followed by either a left or right traversal are NOT letters in the word. For example, consider the path in the tree below that traverses the nodes containing m, t, a, g, b. The letter m is not in the word because the next branch is to the right. The letter g is also not in the word because the next branch is to the left. All other letters are in the word, and as such, the word corresponding to that path is tab.

m

b i t

a y x o a

t m g

s b

This tree contains words:

as, at, by, mix, mom, tab, tag

To find a word in this structure: If the current node character k matches the current string character c then search for the rest of the string in the middle subtree. Otherwise, search for the string in the left or right subtree, depending on whether k is less or greater than c, respectively. You have found a word if you have found all the characters of your string, and if the current node has no middle child. Note that our version of a TST is really a simplification because it only stores words which are not prefixes of other words in the dictionary. That is, our tree cannot contain the words “cap” and “cape” because cap is a prefix of cape. A slight modification of our structure would eliminate this constraint, but we’ll not bother with that here.

ii. (10 points) Write the private version of the find function here:

Solution: bool TST::find(const string & s, TSTNode* t, int strPos) { if(t == NULL) return false; if(s[strPos] == t->k) { if(strPos+1 >= (int)s.length()) return (t->mid == NULL); return find(s, t->mid, strPos+1); } else if(s[strPos] < t->k) return find(s, t->left, strPos); else return find(s, t->right, strPos); }

Rubric: 2pts - preventing segfaults and handling NULL pointers properly in all locations 2pts - checking t->mid is NULL in the last node before returning true 2pts - properly traversing the tree 1pt - comparing the (strPos)th character with t->k 3pts - satisfactory comments to explain your code’s logic -1pt - recursing on multiple children of a single node -1pt - syntax and minor logic errors -2pt - major logic errors -1pt - comments containing false statements -1pt - not using a proper function header

Note: Logic errors include properly chaining return values. Syntax errors include the compiler error where execution reaches the end of non-void functions.

  1. [Iterators – 10 points].

(a) (4 points) Containers in the C++ Standard Template Library typically provide access to their contents though objects called iterators. A forward iterator is guaranteed to implement the assignment operator and four other operators. List those other four op- erators:

Solution: * (dereference), ++, ==, !=

Rubric: 1 point each

(b) (6 points) The inclusive prefix sum problem is stated as follows: Given a list of n numbers a 0 , a 1 ,... , an− 1 compute a list a 0 , a 0 + a 1 , ...., a 0 + a 1 + ... + an− 1. In other words each item in the list has the sum of all the previous items added to it. The following code uses an STL list and a list iterator to compute the inclusive prefix sum in-place (the input list structure is also used for the output). Fill in the blanks so that the code works correctly.

#include using namespace std;

void incl_prefix_sum(list & items) { int prefix = 0; for(__1__iterator itr = items.2; itr 3 items.end(); 4) { 5a = prefix + 5b; prefix = 6; } }

Solution:

  1. list::
  2. begin()
  3. !=
  4. itr++ 5a. *itr 5b. *itr
  5. *itr

Rubric: 1 point each (5a and 5b together are 1 point)

Now we need to move up the tree and check the balance of 80. 80 is unbalanced, and the part that is too long is the left subtree of the left child, so we need to perform a right rotation about 80. This rotation gives the tree below, and since we have worked our way up to the root, it is the final tree.

Rubric: 1 pt for removing 86 2 pts for recognizing 90 is out of balance 3 pts for using right-left rotation to balance 90 2 pts for recognizing 80 is now out of balance 2 pts for using right rotation to balance 80 Miscellaneous deductions: –not marking the out-of-balance nodes (1 pt) –rotating about wrong nodes (1-5 pts)

(b) (5 points) An AVL tree is a special kind of binary search tree. Explain why the rotations we perform don’t destroy the BST-ness of the tree. (Hint: Some pictures might help make your explanation clearer.)

Solution: It suffices to show that the BST properties are conserved in a right rotation, since left and right rotations are symmetric and right-left and left-right rotations are simply combinations of left and right rotations. Suppose we have the first tree below, with A, B, C, and D all having the same height (so the tree is too long in the left subtree of the left child of the root). This tree needs a right rotation to put it into balance, and the tree after this rotation is shown in the second image. We are assuming that the first tree is a BST, so X < Y < Z, everything in A is less than X, everything in B is between X and Y, everything in C is between Y and Z, and everything in D is greater than Z. But these are exactly the conditions that we need for the second tree to be a BST. Thus a right rotation does not destroy the BST-ness of a tree, and so all AVL rotations conserve the BST properties.

Rubric: 2 pts for considering all cases (through symmetry or brute force) 1 pt for showing that nodes involved retain BST property 2 pts for showing that children/subtrees of nodes involved retain BST property Miscellaneous deductions: –showing that resulting trees are binary trees, not BSTs (4 pts) –not specific about how the rotations preserve the BST properties (2-4 pts)

  1. [Blue-Orange Trees – 20 points].

A Blue-Orange Tree is a binary tree where each node contains a color label whose value is either orange or blue. In this problem you will complete the code for a public member function of the BOTree class called mostOrange that, for a BOTree T returns a pointer to the root of the subtree whose %-age of orange nodes is largest among all subtrees of T (note that this subtree need not be a rooted at a child of T ). We have given you a partial class definition for the BOTree class, including the public member function called mostOrange that finds the subtree in a BOTree object whose %-age of orange nodes is maximized. Your task is write the two private member functions that are used by mostOrange. Ties may be broken arbitrarily. If the root is null return null. You may write any helper functions you wish. Be sure to comment your code because it is worth approximately one fourth of the points. You may use the function isOrange to test the color value of a node.

class BOTree { public: class BOTreeNode { public: ... BOTreeNode* left; BOTreeNode* right; bool isOrange();

int orangeNodes; int totalNodes; };

BOTreeNode * mostOrange() {

// Count # of orange and total nodes in tree rooted at root. void setColorCount(root);

// return a pointer to the subtree of root whose percentage of oranges is maximal BOTreeNode * mostOrange(root,best); } ...

private:

BOTreeNode * root;

void setColorCount(BOTreeNode * root); BOTreeNode * mostOrange(BOTreeNode * root, double & max);

};

(a) (8 points) Write the function setColorCount as declared above.

Solution: void setColorCount (BOTreeNode* root){ //Terminating condition if(root == NULL) return;

//Tree traversal if(root->left != NULL) setColorCount(root-left); if(root->right != NULL) setColorCount (root->right);

//Initializing values in root root->orangeNodes = root->isOrange()?1:0; root->totalNodes = 1;

//Updating values after the traversal if(root->left != NULL){ root->orangeNodes + = root->left->orangeNodes; root->totalNodes + = root->left->totalNodes; }

if(root->left != NULL){ root->orangeNodes + = root->right->orangeNodes; root->totalNodes + = root->right->totalNodes; }

return; } Rubric: 1 pt for terminating condition in the recursion 2 pts for only accurate tree traversal 1 pt for initializing orangeNodes and totalNodes 2 pts for updating orangeNodes and totalNodes 2 pts for proper comments