To start with, I am trying to read a binary tree from file (noob question, I know, but I dont know what I am doing wrong), but it does not work at all, it keeps crashing. The thing is, I got to read the family tree from the file and then put it in preorder, inorder and post order accordingly.For now I am trying to do it with integers, one step at a time. The problems seems to be at my create function, which is:
NodeT *createBinTree(int branch, NodeT *parent) {
int id;
FILE *f;
f=fopen("data.in","r");
while (!feof(f)) {
fscanf(f,"%d",&(parent->id));
fscanf(f,"%d",&id);
if (id == 0)
return NULL;
else {
p = (NodeT*)malloc(sizeof(NodeT));
if (p==NULL)
fatalError("Out of space in createBinTree");
p->id = id;
p->left = createBinTree(1, p);
p->right = createBinTree(2, p);
}}
close(f);
return p;
}
The function that I had was reading it from input stream, like:
NodeT *createBinTree(int branch, NodeT *parent) {
if (branch == 0)
printf("Root identifier [0 to end] = ");
else
if (branch == 1)
printf("Left child of %d [0 to end] =", parent->id);
else
printf("Right child of %d [0 to end] =", parent->id);
scanf("%id", &id);
if (id == 0)
return NULL;
else {
p = (NodeT *)malloc(sizeof(NodeT));
if (p == NULL)
fatalError("Out of space in createBinTree");
p->id = id;
p->left = createBinTree(1,p);
p->right = createBinTree(2,p);
}
return p;
}
But it seems I don't really know how to transfigure the latest so it can read from file. Any help will be much appreciated. How I am calling the function:
NodeT *root;
root = createBinTree(0, NULL);
For reference, my data.in is: 1 2 4 8 0 0 9 0 0 5 10 0 0 11 0 0 3 6 12 0 0 13 0 0 7 14 0 0 15 0 0. Please be nice, I am a newbie at this. :c