我实现了二叉搜索树,但我的节点删除功能无法正常工作:
void remove_node(treePointer *root, element data)
{
treePointer next, temp;
treePointer *left;
treePointer *p = root;
treePointer removed;
// while(1)
// {
// if(*p == NULL)
// {
// printf("error\n");
// return;
// }
// else if((*p)->data == data)
// break;
// else if((*p)->data > data)
// p = &((*p)->left_child);
// else
// p = &((*p)->right_child);
// }
removed = search(*root, data);
p = &removed;
if((*p)->left_child == NULL)
next = (*p)->right_child;
temp = *p;
*p = next;
free(temp);
}
使用已注释的代码可以正确执行删除,但使用search()
函数(如下)则不会。
treePointer search(treePointer root, element data)
{
if(!root) return NULL;
if(data == root->data) return root;
if(data < root->data)
return search(root->left_child, data);
return search(root->right_child, data);
}
这是结构定义:
typedef int element;
typedef struct tree *treePointer;
typedef struct tree
{
element data;
treePointer left_child;
treePointer right_child;
} tree;
出了什么问题?