使用 free(N) 删除 BST 中的节点
我正在编写二叉搜索树,但在寻找有效删除节点的方法时遇到了一些麻烦。
我有这段代码:
struct node* deleteNode(int i, struct node *N)
{
if (N==NULL)
{
return NULL;
}
else if (i<N->value)
{
N->size--;
N->lChild=deleteNode(i,N->lChild);
}
else if (i>N->value)
{
N->size--;
N->rChild=deleteNode(i,N->rChild);
}
else if (N->lChild==NULL)
{
return N->rChild;
}
else if (N->rChild==NULL)
{
return N->lChild;
}
else
{
N->size--;
N->value=findMin(N->rChild);
N->rChild=deleteNode(N->value,N->rChild);
}
return N;
}
N 是一个节点结构,有 5 个字段:值、lChild、rChild、大小、高度。 事实上,我在这里所做的是使树不指向我想要删除的节点,但是当我尝试放置类似以下内容时:
else if (N->rChild==NULL)
{
free(N);
N=NULL;
return N->lChild;
}
或每个类似的代码,它不起作用。有人可以指出我正确的方向吗? 谢谢。
I'm coding a binary search tree and I'm having a little trouble finding a way to delete node effectively.
I have this code :
struct node* deleteNode(int i, struct node *N)
{
if (N==NULL)
{
return NULL;
}
else if (i<N->value)
{
N->size--;
N->lChild=deleteNode(i,N->lChild);
}
else if (i>N->value)
{
N->size--;
N->rChild=deleteNode(i,N->rChild);
}
else if (N->lChild==NULL)
{
return N->rChild;
}
else if (N->rChild==NULL)
{
return N->lChild;
}
else
{
N->size--;
N->value=findMin(N->rChild);
N->rChild=deleteNode(N->value,N->rChild);
}
return N;
}
And N is a node structure which have 5 fields : value, lChild, rChild, size, height.
In fact what I'm doing here is to make the tree not to point toward the node that I want to delete but when I'm trying to put something like :
else if (N->rChild==NULL)
{
free(N);
N=NULL;
return N->lChild;
}
Or every similar looking code, it doesn't work. Can someone point me in the right direction please?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您说 N=NULL ,然后调用 N->lchild N 为 null 并指向任何内容,那么您期望如何获得 lchild 值?
由于这是作业,我不会给出直接答案,而是给出提示。
要删除该节点,请检查它是否有子节点,如果没有则释放它并删除对其的引用,例如父节点指针。
如果它有 1 个子节点,则将指向要删除的节点的 ptr 与子节点交换并释放该节点。如果您还有 2 个孩子,同样适用。
First of all you're saying N=NULL and then calling N->lchild N is null and pointing to nothing so how do you expect to get the lchild value?
Since this is homework I won't give a direct answer but hints.
To delete the node, check if it has children, if it doesnt free it and remove references to it such as the parents child ptr.
If it has 1 child swap the ptr that points to the node you want to delete with the child and free the node. The same applies if you also have 2 children.