CS360 Midterm -- March 14, 2002. Answer/Grading for Question 5
Answer
Ok, this is a serialization of a red-black tree. For
each node of the first-level tree, writer() writes
the key, then it writes the number of nodes in the red-black tree
held in the val. Finally, it writes out each key/val pair in
the second-level tree.
So, reader() must read one of these files and rebuild the
tree. It reads a key and a number of nodes, then reads those
nodes into a fresh red-black tree. Then it inserts this tree
with the given key into the first-level tree. Here's the code:
JRB reader(FILE *f)
{
JRB t1, t2;
int key1, n;
double key2, val2;
t1 = make_jrb();
while (fread(&key1, sizeof(int), 1, f) == 1) {
if (fread(&n, sizeof(int), 1, f) != 1) return NULL;
t2 = make_jrb();
for (i = 0; i < n; i++) {
if (fread(&key2, sizeof(double), 1, f) != 1) return NULL;
if (fread(&val2, sizeof(double), 1, f) != 1) return NULL;
jrb_insert_dbl(t2, key2, new_jval_d(val2));
}
jrb_insert_int(t1, key1, new_jval_v((void *) t2));
}
return t1;
}
Note, I didn't say what to do if the input file has issues -- I
decided to return NULL. Any reasonable
way you wanted to deal with it is fine.
Grading -- 11 points
- Making a first-level tree: 1 point
- Reading the first key: 1 point
- Exiting/returning when fread() returns zero here: 1 point
- Reading the number of second-level nodes: 1 point
- Creating a second-level tree: 1 point
- Having a loop to read in the key/val pairs: 1 point
- Reading the second-level key: 1 point
- Reading the second-level val: 1 point
- Inserting them into the second-level tree: 1 point
- Inserting the proper values into the first-level tree: 1 point
- Testing the return values of fread() and doing something
reasonable: 1 point
As always, if random pieces are there, but incoherently connected,
then points were deducted.