Here is what I have so far for the structures that I will use:
CODE
typedef struct
{
char key;
// Some other data
} TreeEntry;
typedef struct node_q
{
struct node_s
{
struct node_q *element;
struct node_s *next;
};
TreeEntry entry;
struct node_s *childs;
struct node_q *parent;
} Vertex;
struct node_s;
typedef struct node_s node_t;
typedef struct
{
Vertex *root;
} Tree;
And this is the code for the function that will read an expression from a file and represent as a tree, for example:
(A(B(E(K,L),F),C(G),D(H(M),I,J))) where the siblings are separated with commas, and the children are put in nested parenthesis.
Here what I came up with for the function that will do this job:
CODE
void Load(char *dir, Tree *t)
{
FILE *inp;
char str[MAXSIZE];
int i;
Vertex *w;
node_t *c;
inp = fopen(dir, "r");
fgets(str, MAXSIZE, inp);
for (i = 0; i < strlen(str); ++i)
{
if (t->root == NULL)
{
if (str[i] == '(')
{
t->root = (Vertex *)malloc(sizeof(Vertex));
t->root->childs = NULL;
t->root->parent = NULL;
w = t->root;
}
}
else
{
if (str[i] == '(')
{
c = w->childs;
c = (struct node_t *)malloc(sizeof(node_t));
c->next = NULL;
c->element = (Vertex *)malloc(sizeof(Vertex));
c->element->childs = NULL;
c->element->parent = w;
w = c->element;
}
else if (isalpha(str[i]))
{
w->entry.key = str[i];
}
else if (str[i] == ',')
{
w = w->parent;
c = w->childs;
while (c->next)
c = c->next;
c->next = (struct node_t *)malloc(sizeof(node_t));
c = c->next;
c->next = NULL;
c->element = (Vertex *)malloc(sizeof(Vertex));
c->element->childs = NULL;
c->element->parent = NULL;
w = c->element;
}
else if (str[i] == ')')
{
w = w->parent;
}
}
}
}
Thanks in advance for your help.