简体   繁体   中英

Binary Search Tree

so i coded a binary search tree in C which looks with this struct:

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). My searchnode method is supposed to move a pointer to the "50" so i can delete it afterwards. However my searchnode Method only returns the pointer if the element im searching is the root of my binary search tree.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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