Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
0 of .
Results for:
P. 1
h39 final exam solutions

# h39 final exam solutions

Ratings: (0)|Views: 37|Likes:

### Availability:

See more
See less

02/01/2013

pdf

text

original

CS106B
Handout #39
Yves Lu
August 21, 2008
Final Examination Solutions
1. (Thanks Sarah!)
template <typename ValueType>

double PercentMultiple(Map<Vector<ValueType> > &map) {
double total = map.size();
Map<Vector<ValueType> >::Iterator iter = map.iterator();
int multiple = 0;
while(iter.hasNext())

if(map[iter.next()].size() > 1)
multiple++;
return multiple/total;
}2a. (Thanks Sarah!)
listNodeT* TreeToListBFS(treeNodeT* root) {
if(root == NULL) return NULL;

listNodeT* cur;
Queue<treeNodeT *> q;
q.enqueue(root);
while(!q.isEmpty()) {

treeNodeT *node = q.dequeue();

listNodeT *next = new listNodeT;
next->name = node->name;
next->next = null;

if(node==root) { //special case for the first node

}else cur->next = next;
cur = cur->next;
if(node->left != null) q.enqueue(node->left);
if(node->right != null) q.enqueue(node->right);
}
2b.
Exponential Time Version
void deleteTree(nodeT*& root)

{
if (root == NULL) return;
deleteTree(root->left);
deleteTree(root->right);
delete root;
root = NULL;

}void deleteOverlap (nodeT*& root1, nodeT*& root2)
{
if (root1 == NULL || root2 == NULL) return;

if (root1->name == root2->name) {
deleteTree(root1);
deleteTree(root2); // or root2 = NULL;

}deleteOverlap(root1->left, root2);

deleteOverlap(root1->right, root2);
deleteOverlap(root1, root2->left);
deleteOverlap(root1, root2->right);

}
2b.
Polynomial Time Version (Thanks Tim!). Using TreeToListBFS seems to be more trouble than
it\u2019s worth because you have to deal with **.
void deleteList(listNode * & h1)

{
if(h1 == NULL) return;
deleteList(h1->next);
delete h1;
h = NULL;

}nodeT** findLink(nodeT** h, string & name)

{
if(*h == NULL) return NULL;
if((*h)->name == name) return h;
nodeT** kid;
if((kid = findLink(h->left,name)) != NULL) return kid;
if((kid = findLink(h->right,name)) != NULL) return kid;

return NULL;
}void deleteOverlap (nodeT*& root1, nodeT*& root2)

{
listNode * h1 = TreeToListBFS(root1);
listNode * h2 = TreeToListBFS(root2);

bool found = false;
string name = "";
for(listNode * i1 = h1; i1 != NULL && !found; i1=i1->next){

for(listNode * i2 = h2; i2 != NULL && !found; i2=i2->next){

if(i1->name == i2->name){
name = i1->name;
found = true;

}
}
}deleteList(h1);
deleteList(h2);

if(found){