I\'m trying to construct a full binary tree (full meaning that every non leaf node has two leaf nodes connecting to it, i.e. node->right
and node->left<
There are some problems in your code:
you should use ungetc()
instead of fseek()
to backtrack by one character to avoid failure on streams that do not support seeking.
you should write (check == '(')
instead of hard coding the ASCII character value. It is both more portable and more readable.
To avoid undefined behavior, you should check for EOF
and for fscanf()
parsing success. As a matter of fact, this would avoid the need for the test on check
.
When you parse a leaf node, you should not recurse and parse further nodes below the current one.
index
seems redundant as the sequence of nodes should suffice to full determine where to stop.
Here is a modified version:
Node *constructTreeHelper(FILE *infile, int *index) {
double lwire, rwire;
int sink;
double cap;
Node *node;
// Base case
if (*index <= 0) {
// This test seems redundant with the file contents */
return NULL;
}
// this fscanf will fail on the byte byte if it is not a '('
if (fscanf(infile, " (%le %le)", &lwire, &rwire) == 2) {
// If the node is not a leaf node
node = createNode(0, 0, lwire, rwire);
*index -= 1;
node->right = constructTreeHelper(infile, index);
node->left = constructTreeHelper(infile, index);
} else if (fscanf(infile, "%d(%le)\n", &sink, &cap) == 2) {
// If the node is a leaf node
node = createNode(sink, cap, 0, 0);
*index -= 1;
} else {
// invalid format or end of file */
node = NULL;
}
return node;
}