I’m trying to make a search method using a binary tree(no, it’s not a binary search tree, just a binary tree) using a recursive function. If the data is on the binary tree, i want it to return the node and if it is not, i want it to return a NULL value. I have made the search function and it’s doing its job perfectly. But the problem is, it seems that the function won’t return the node.
Here’s the struct for the binary tree:
struct data
{
int number;
struct data *left, *right;
}*root = NULL;
and this is the search function i’m talking about:
data* search(struct data *node, int key)
{
if(node == NULL)
return NULL;
else
{
printf("\n%d %d -", node->number, key);
if(node->number== key)
return node;
search(node->left, key);
search(node->right, key);
}
}
When i’m calling the search function like this: search(root, 6); , it says that it’s returning a NULL value although i have pushed a 6 number into the binary tree(and the search function stops right at the return node; line too, so i’m assuming that the function is returning a NULL.)
I have seen a tutorial for binary tree in here , used and changed some code from it, but it’s still the same. i’m desperately looking for help right here 🙁
Your function will always returnYour function does not do anything with the results from its recursive invocations; in fact, control flow may “fall off the end” of it without hitting aNULL, except when the top node contains the key.returnstatement.You should check the return values from the recursive invocations and pass those up when appropriate:
Note the “ternary operator” (if-then-else expression)
?:.