【发布时间】:2016-07-26 12:54:44
【问题描述】:
我编写了一个二叉搜索树并创建了一个删除节点的函数。 一般它有两个输入参数,第一个是指向需要删除的对象的指针,第二个是指向二叉搜索树根的指针。
除了节点是叶子的“最简单”的情况外,基本上我的所有情况都有效。
我的代码将应该删除的节点的内容设置为0,但是仍然有对此的引用并且它显示在树中。
*p 是应该被删除的元素。
*pBaum 指向树的根。
*p-> right 和 *p->left 是指向 *p 的左右子树的指针。
*p->conten 是 *p 的值。
叶子案例中的我的代码:
struct tnode *deletenode(struct tnode *p, struct tnode *pBaum)
{
if (p !=NULL)
{
if ((p->left == NULL) && (p->right == NULL))
{
printf("%d Ist Blatt \n", p->content);
free(p);
return pBaum;
}
基本上我“只”需要告诉指针 *p 它从现在开始无效。但是我无法找到合适的解决方案。也许你们可以帮忙。
编辑:好的,我自己尝试过将父指针设置为 NULL。
struct tnode* danglingPointerFix (struct tnode *p, int nodtodelete)
{
if((p->right)->content = nodtodelete)
{
p->right = NULL;
return 0;
}
if((p->left)->content = nodtodelete)
{
p->left = NULL;
return 0;
}
}
struct tnode *searchnode(struct tnode *p, int nodtodelete)
{
if (p == NULL)
{
printf("Baum ist leer oder Element nicht vorhanden \n");
return 0;
}
if ( p -> content == nodtodelete)
{
return p;
}
if (p->content < nodtodelete)
{
danglingPointerFix(p, nodtodelete);
return searchnode (p->right, nodtodelete);
}
if (p->content > nodtodelete)
{
danglingPointerFix(p, nodtodelete);
return searchnode(p->left, nodtodelete);
}
}
但是我有段错误,也许在某个地方可以看到,因为在我看来这个解决方案应该可以工作。
【问题讨论】:
-
是否有理由将指针设置为 NULL 不是一个可行的选项?但也许你看错了。通常在维护这样的树时,您会设置左右节点的指针,以便它们不再引用已删除的节点。
-
你没有忘记对
p的引用吗? -
0XDEADBEEF 有时用于将指针标记为无效
-
@BobJarvis 我试过了,但没用。问题是 *p 是一个指向节点的指针,但它并没有告诉 p-> right 或 p->left 来自前一个节点的指针它是无效的。
-
@Cornstalks:我正在编辑我的评论,试图轻轻地引导 OP 朝那个方向发展。
标签: c pointers binary-search-tree nodes