How can I return a tree node when I found it?
So, I have a binary tree and, when I search in the tree what I searched for was found I want to return the pointer to that node, so I can usa that node in other function. There is my search function:
Tnode *Tsearch(Tnode *r, char *word) {
if(r == NULL) {
printf("%s NOT FOUND\n", word);
return NULL;
}
int comp = strcasecmp(r->word, word);
if( comp == 0) {
printf("%s FOUND\n", r->word);
return r;
}
else if( comp > 0) {
Tsearch(r->left, word);
}
else if( comp < 0) {
Tsearch(r->right, word);
}
return 0;
}
My problem is that when I try to use the return of the function Tsearch it doesn't work and I really can't understand why and how to solve it.
The function where I want to use that returned node from the search function is the following:
int Tsearch_ref(Tnode *r, char (*words)[30]) {
if(r == NULL) {
return 0;
}
printf("%s, %d", words[0], (int)strlen(words[0]));
Tsearch(r,words[0]);
auxT = Tsearch(r,words[0]);
Lnode *aux = auxT->head;
printf("Title: %s\n", ((Book *)aux->ref)->title);
while(aux != NULL) {
aux_arr[i].ref=aux->ref;
printf("Title: %s\n", ((Book *)aux_arr[i].ref)->title);
printf("%p\n", &(aux_arr[i].ref));
aux = aux->next;
i++;
}
}
This function is not complete because I was trying to solve the return problem, but basically I want to take that tree node that have a list inside and put that list into a temporary array.
The structures are the following:
typedef struct {
char *title;
char isbn13[ISBN13_SIZE];
char *authors;
char *publisher;
int year;
} Book;
typedef struct lnode {
struct lnode *next;
void *ref;
} Lnode;
typedef struct tnode {
struct tnode *left;
struct tnode *right;
char *word;
Lnode *head;
} Tnode;
It's my first question here in StackOverflow, so if you need any more info about anything I will obviously provide it.
Thanks in advance!
You need to change the recursive calls to Tsearch to actually return the found node. So, instead of this code:
else if( comp > 0) {
Tsearch(r->left, word);
}
else if( comp < 0) {
Tsearch(r->right, word);
}
do this:
else if( comp > 0) {
return Tsearch(r->left, word);
}
else if( comp < 0) {
return Tsearch(r->right, word);
}
Note that if your tree is very deep, you may use up the entire call stack and throw an exception.
Why not use while loop?
Tnode *Tsearch(Tnode *r, char *word) {
Tnode *cur = r;
int comp;
while (cur != NULL)
{
if ((comp = strcasecmp(cur->word, word)) == 0)
{
printf("%s FOUND\n", cur->word);
return cur;
}
else if (comp > 0)
{
/* Move to the left child */
cur = cur->left;
}
else
{
/* Move to the right child */
cur = cur->right;
}
}
printf("NOT FOUND\n");
return NULL;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With