二进制搜索树节点删除错误

时间:2016-07-14 21:50:42

标签: c pointers binary-tree binary-search-tree

我已经创建了我的二叉搜索树,并将指向我要删除的节点的指针提供给我的*p

删除方法应该是删除*p指向的节点,并且应该将addtree的子树添加到我的根。 *pBaum是指向我的根的指针。

但是,每次我声明

时,我都会在addtree上收到一条名为“冲突类型”的错误消息
Baum = addtree(Baum, p->right);

我也收到警告“赋值从没有强制转换的整数中生成指针”

我的结构包含left&指向子树的右指针和指向内容的指针。

struct tnode
{
int content;
struct tnode *left; /* linker Teilbaum */
struct tnode *right; /* rechter Teilbaum */
};

// Deletes the node where *p is pointing at

struct tnode  *deletenode(struct tnode *p, struct tnode *pBaum)
{
   struct tnode *Baum = pBaum;

    if ((p->left == NULL) && (p->right == NULL))
    {
      free(p);
    }
    if ((p->left == NULL) && (p->right != NULL))
    {
      Baum = addtree(Baum, p->right);
      free(p);

    }
    if ((p->right == NULL) && (p->left !=NULL))
    {
      Baum = addtree(Baum, p->left);
      free(p);
    }
    if ((p->left != NULL) && (p->right !=NULL))
    {
      Baum = addtree(Baum, p->right);
      Baum = addtree(Baum, p->left);
      free(p);
    }
  return Baum;
}

// Adds the Subtrees to my root

struct tnode *addtree(struct tnode *top, struct tnode *p)
{
if (p == NULL)
    return top;
else
return addtree(addtree(addelement(top, p->content),p-> right),   p->left);

// Adds a node to my Tree

struct tnode *addelement(struct tnode *p, int i)
{
int cond;
if (p == NULL)
{
    p = talloc(); /* make a new node */ p->content = i;
    p->left =p->right =NULL;
}
else if (p->content == i)
{
    return p;
}
else if (i < p->content) /* goes into left subtree */ p->left =addelement(p->left, i);
else /* goes into right subtree */ p->right = addelement(p->right, i);
return p;
}

// Looks for the node which is supposed to get deleted and returns a pointer to it 

struct tnode *searchnode(struct tnode *p, int nodtodelete)
{
if (p == NULL)
{
    printf("Baum ist leer oder Element nicht vorhanden \n");
    return NULL;
}
if ( p -> content == nodtodelete)
{
    return p;
}
if (p->content < nodtodelete)
{
    return searchnode (p->right, nodtodelete);
}
if (p->content > nodtodelete)
{
    return searchnode(p->left, nodtodelete);
}
}
}

int main()
{
struct tnode *Baum = NULL;
struct tnode *tmpPos = NULL;
Baum = addelement (Baum, 32);
Baum = addelement(Baum, 50);
Baum = addelement(Baum, 60);
tmpPos = searchnode(Baum,50);
Baum = deletenode(tmpPos, Baum);
}

2 个答案:

答案 0 :(得分:0)

您是否在代码中的函数调用之前声明了该函数?我在文件顶部声明了addtree和addelement函数,并且冲突类型的错误消失了。

答案 1 :(得分:0)

我不确定这是否是由于您只包含部分代码,但您的addtree函数未完成:

struct tnode *addtree(struct tnode *top, struct tnode *p)
{
if (p == NULL)
    return top;
else
return addtree(addtree(addelement(top, p->content),p-> right),   p->left);

此功能需要用括号结束:

struct tnode *addtree(struct tnode *top, struct tnode *p)
{
    if(p == NULL)
        return top;
    return addtree(addtree(addelement(top, p->content), p->right), p->left);
}

为了使编译器不会抱怨没有在非void函数中返回值,最好还是去除else。