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

As always, if random pieces are there, but incoherently connected, then points were deducted.