So I'm trying to create a linked list from a binary tree using preorder tranversal. I'm having so many problems at doing it, I saw some of the "solutions" but I didn't like it! I am trying something simple.
This is the code that I got until now:
typedef struct nodo {
int value;
struct nodo *left, *right;
} *ABin;
typedef struct lligada {
int value;
struct lligada *next;
} *LInt;
void preorder (ABin a, LInt * l) {
LInt r=*l,tmp;
tmp=r;
if (!a) {
*l=NULL;
}
else {
r=malloc(sizeof(struct lligada));
r->value=a->value;
r=r->next;
*l=tmp;
preorder (a->left,l);
preorder (a->right,l);
}
}
I'm getting always an empty list!
if (!a) { *l=NULL; }
This will allways be the last thing done in your function, with the null in *l being passed all the way up.
The rest also has problems:
r=r->next;
But you never set r->next
to anything. You'll have to do that first.
Further, when you first call preorder()
what, if anything, is *l
pointing to? You'd probably be better off, instead of passing in a LInt*, having the function return a Lint* (joining the lists after the internal calls to preorder()
)