I am trying to delete a node from a binary search tree. But when I want to test the function, I'll get an error message in 'case 3: two children'.
clist->name = temp->name;
This line causes the error message. It says: the left operand has to be an l-value. I am new to C and binary search trees. I can't figure out, why this line is not working. I found many ideas on the internet how to implement a delete function. And all those approaches uses this line of code.
Following is the complete function.
(greaterThan, lessThan, toLowerCase are helper function what I implemented. And they are working fine for sure)
struct student {
int ID;
char name[20];
struct student *left;
struct student *right;
};
struct student * minValueNode(struct student* node) {
struct student* current = node;
while (current->left != NULL)
current = current->left;
return current;
}
struct student * bst_delete (struct student *clist, char* token, struct student **parent)
{
if (clist == NULL)
return clist;
char* clistName = clist->name;
char* tok = token;
toLowerCase(clistName);
toLowerCase(tok);
if (lessThan(tok, clistName))
clist->left = bst_delete(clist->left, token, &clist->left);
else if (greaterThan(tok, clistName))
clist->right = bst_delete(clist->right, token, &clist->right);
else
{
//Case 1: No children
if (clist->left == NULL && clist->right == NULL) {
free(clist);
clist = NULL;
}
//Case 2: One Child
if (clist->left == NULL) {
struct student *temp = clist;
clist = clist->right;
free(temp);
} else if (clist->right == NULL) {
struct student *temp = clist;
clist = clist->left;
free(temp);
}
//Case 3: Two Children
else {
struct student *temp = minValueNode(clist->right);
clist->name = temp->name;
clist->right = bst_delete(clist->right, temp->right, &clist->right);
}
}
return clist;
}
It would be great if anybody could tell me why this line is not working. And how I could fix this error.
Thank You!
You can't copy an array in c through direct assignment, what you really want to do is copy the elements of the array - for that you could use strcpy -
strcpy(clist->name, temp->name);
or since the size is constant, use the slightly safer -
strncpy(clist->name, temp->name, 20);
Actually you were lucky here, you could have used pointers for your name strings (allocating them dynamically), which would have made that assignment valid code (though still not copying the string contents as you want, just overriding one pointer with the other) and allow the code to compile, but would have then caused you memory leaks and sharing pointers between the nodes - that would have been much harder to debug.
In this case, the right hand value in the assignment may decay to a pointer, but the left hand value can not (since that array is statically placed inside the struct), so the compiler is complaining about the l-value.