I am working on a function that searches through a binary search tree in C for a name that is passed in with the function. However, I am stuck on how to format my loop so that the recusion doesn't simply end when the traversal reaches the left-most node with no children. The traversal has to be pre-order (visit myself, then my left child, then my right child).
My find function is as follows:
tnode *bst_find_by_name(tnode *ptr, const char *nom){
if(ptr != NULL){
if(strcmp(ptr->name, nom) == 0){
return ptr;
}
if(ptr->left != NULL){
return bst_find_by_name(ptr->left, nom);
}
if(ptr->right != NULL){
return bst_find_by_name(ptr->right, nom);
}
}
return NULL;
}
As you can see, currently this simply returns NULL once it reaches the left-most node that does not match the string that was passed into the function. I have to have it return NULL if it does not find a match in the tree, but at the same time I do not want it to return NULL too early before it has a chance to search every node in the tree. Any ideas?