简体   繁体   English

二进制搜索树

[英]Binary Search Tree

so i coded a binary search tree in C which looks with this struct: 所以我用C编写了一个二进制搜索树,它的结构如下:

struct tnode {
    int content;
    struct tnode *left; /* left tree part */
    struct tnode *right; /* right tree part */
};

My main method: 我的主要方法:

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);
}

So basicly this creates me a Binary search tree with 3 elements (32,50,60). 因此,从根本上来说,这会创建一个具有3个元素(32,50,60)的Binary搜索树。 My searchnode method is supposed to move a pointer to the "50" so i can delete it afterwards. 我的searchnode方法应该将指针移到“ 50”,以便以后可以删除它。 However my searchnode Method only returns the pointer if the element im searching is the root of my binary search tree. 但是,如果我正在搜索的元素是我的二进制搜索树的根,则我的searchnode方法仅返回指针。

searchnode: searchnode:

struct tnode *searchnode(struct tnode *p, int nodtodelete) {
    if (p == NULL) {
        printf("Baum ist leer oder Element nicht vorhanden \n");
    }

    if ( p -> content == nodtodelete) {
        return p;
    }

    if (p->content > nodtodelete) {
        searchnode (p->right, p->content);
    }
    if (p->content < nodtodelete) {
        searchnode(p->left, p->content);
    }
}

Maybe you guys can help me. 也许你们可以帮我。

You should pass the value you're searching for, not the value of the node: 您应该传递要搜索的值,而不是节点的值:

searchnode (p->right, nodtodelete);
                      ^

Make the same change to the other recursive call. 对其他递归调用进行相同的更改。

searchnode(p->left, nodtodelete);

Your function has undefined behavior since it doesn't have any return statements in the recursive calls. 您的函数具有未定义的行为,因为在递归调用中没有任何return语句。

Also, the recursive calls need to be fixed to use the right input. 同样,递归调用需要固定以使用正确的输入。

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;
   }

   // This is copied from OP's question but it seems suspect.
   // It should probably be:
   // if (p->content < nodtodelete)
   if (p->content > nodtodelete)
   {
      return searchnode (p->right, nodtodelete);
   }

   return searchnode(p->left, nodtodelete);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM