我在二叉搜索树中有一个删除节点函数,如下所示:
struct Node *_removeNode(struct Node *curr, TYPE val) {
/* FIX ME */
printf("curr->val: %.1f...%p\t val: %.1f\n", curr->val, curr, val);
struct Node* to_del = NULL;
if(val < curr->val){
return _removeNode(curr->left, val);
} else if( val > curr->val) {
return _removeNode(curr->right, val);
} else {
//case 1 -> curr is a leaf
if(curr->left == NULL && curr->right == NULL){
printf("removed %.1f\n", curr->val);
to_del = curr;
free(to_del);
}
//case if left node is not null but right is
if(curr->left != NULL && curr->right == NULL){
to_del = curr;
printf("to_del: %p...%.1f\t", to_del, to_del->val);
curr = curr->left;
printf("new curr: %p...%.1f\n", curr, curr->val);
free(to_del);
}
//case if right node is not null but left is
if(curr->left == NULL && curr->right != NULL){
to_del = curr;
printf("to_del: %p...%.1f\t", to_del, to_del->val);
curr = curr->right;
printf("new curr: %p...%.1f\n", curr, curr->val);
free(to_del);
}
//case both are not not null
if(curr->left != NULL && curr->right != NULL){
to_del = curr;
printf("to_del: %p...%.1f\t", to_del, to_del->val);
curr->right->left = curr->left;
curr = curr->right;
printf("new curr: %p...%.1f\n", curr, curr->val);
free(to_del);
}
}
to_del = NULL;
return to_del;
}
代码应该返回一个指向NULL的指针以传递测试用例,但我尝试的所有内容都会引发内存错误。有没有办法可以将结构设置为NULL然后返回它?
答案 0 :(得分:1)
看看:
if(curr->left == NULL && curr->right == NULL){
to_del = curr;
free(to_del);
}
if(curr->left != NULL && curr->right == NULL){
如果第一个if
为真,那么curr
指向的内存将被释放。如果您在第二个curr->left
中执行,则会出现错误,因为不再有->left
。
也许您应该使用else if
?