Hello,
I have a binary search tree consisting of nodes that contain first and last name of students on a college. Below I've written a function that receives student's last name, and should return pointer to student's node if the student with such last name is found, or NULL if it is not found. I know there's a way better way to do this in a binary search tree (posted at the bottom), but I've decided to play a bit since I need practice with recursive functions. Anyway, the below function doesn't work and I'd appreciate if you could tell me why. After running the program Windows gives me illegal program operation.
The program has been tested with another function that we used in college classes (posted at the bottom), so it works just fine. I'm just curious why my function doesn't work good.
Code:
struct s {
char firstName[25 + 1];
char lastName[25 + 1];
struct s *left;
struct s *right;
};
typedef struct s record;
...
record *search(record *root, char lastName[]) {
if (root) {
if (!strcmp(root->lastName, lastName)) {
printf("Found it!\n");
} else {
root = search(root->right, lastName);
if (root == NULL) {
root = search(root->left, lastName);
}
}
}
return (root);
}
Here's the function that works:
Code:
record *search(record *root, char lastName[]) {
int compare;
if (root) {
compare = strcmp(root->lastName, lastName);
if (compare < 0) {
return (search(root->right, lastName));
} else {
if (compare > 0) {
return (search(root->left, lastName));
}
}
}
return (root);
}