Inc*_*ion 0 c binary-tree pointers
我正在尝试实现二进制搜索树操作并在删除时陷入困境.
11
/ \
10 14
Run Code Online (Sandbox Code Playgroud)
使用inorder遍历作为树的表示最初输出是10 11 14.
删除节点10,输出预期为11 14但我得到0 11 14.
删除节点14,输出预期只有11但我得到0 11 67837.
请解释我输出错误的原因.我不是在找任何代码:).
typedef struct _node{
int data;
struct _node *left;
struct _node *right;
} Node;
Node* bstree_search(Node *root, int key)
{
if(root == NULL){
return root;
}
// Based on binary search relation, key can be found in either left,
// right, or root.
if(key > root->data)
return bstree_search(root->right, key);
else if(key < root->data)
return bstree_search(root->left, key);
else
return root;
}
void bstree_insert(Node **adroot, int value)
{
// since address of address(root is itself address) is passed we can change root.
if(*adroot == NULL){
*adroot = malloc(sizeof(**adroot));
(*adroot)->data = value;
(*adroot)->right = (*adroot)->left = NULL;
return;
}
if(value > (*adroot)->data)
bstree_insert(&(*adroot)->right, value);
else
bstree_insert(&(*adroot)->left, value);
}
void bstree_inorder_walk(Node *root)
{
if(root != NULL){
bstree_inorder_walk(root->left);
printf("%d ",root->data);
bstree_inorder_walk(root->right);
}
}
void bstree_delete(Node **adnode)
{
//Node with no children or only one child
Node *node, *temp;
node = temp = *adnode;
if((*adnode)->right == NULL || (*adnode)->left == NULL){
if((*adnode)->right == NULL){
*adnode = (*adnode)->left;
}else{
*adnode = (*adnode)->right;
}
}else{ // Node with two children
}
free(temp);
}
int main()
{
Node *root = NULL;
Node *needle = NULL;
int i,elems[] = {11,10,14};
for(i = 0; i < 3; ++i)
bstree_insert(&root,elems[i]);
bstree_inorder_walk(root);
printf("\n");
needle = bstree_search(root, 10);
bstree_delete(&needle);
bstree_inorder_walk(root);
printf("\n");
needle = bstree_search(root, 14);
bstree_delete(&needle);
bstree_inorder_walk(root);
printf("\n");
}
Run Code Online (Sandbox Code Playgroud)
请解释我输出错误的原因.
您的delete函数还必须更改已删除节点的父级.例如,删除包含10的节点时,必须将root Node的left子节点设置为NULL.由于不执行此操作,因此在以后遍历树时,将打印出已释放的数据.
我没有查看除了之外的任何代码delete,因此一旦做出此更改,我无法保证其正常工作.