0

if i found the string i just return it if not found I returns 3 suggestions as 1-the last node before declaring that the node is not found 2-the inorder successsor 3- the inorder predecessor

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void line(){printf("\n-------------------------\n");}
typedef struct node node;
struct node{
node* left ,*right;
char *key;
};
node *newnode (char* key){
node *n=malloc(sizeof(node));
n->key=malloc(strlen(key)+1);
strcpy(n->key,key); n->right=n->left=NULL;
return n;
}
node *insirtNode(node *root,char *key){
    if(!root) return newnode(key);
     if(strcmp(key,root->key)<0)      {root->left=insirtNode(root->left,key);}
     else if(strcmp(key,root->key)>0) {root->right=insirtNode(root->right,key);}
    return root;
}
node* search(node *root,char *key,node **pred,node **succ,node **last){
if(root){
       //printf("%s:%s=%d.\n",root->key,key,strcasecmp(key,root->key));
if(strcasecmp(key,root->key)==0){
   printf("%s - is correct",root->key);line(); return root;
}
if(strcasecmp(key,root->key)<0) { if(!root->left){*last=root;} *succ = root;return search(root->left,key,pred,succ,last); }
else {if(!root->right){*last=root;} *pred = root; return search(root->right,key,pred,succ,last);}
  } else return NULL;
}
int main(){
    char input[60];
    printf("enter a word:\n");
    gets(input); line();
    node *pred=NULL,*succ=NULL,*temp=NULL,*last=NULL;

  node *root=NULL;
     root=insirtNode(root,"anas");
     root=insirtNode(root,"anad");
     root=insirtNode(root,"anay");
     root=insirtNode(root,"anaz");
    temp=search(root,input,&pred,&succ,&last);
if (temp != NULL) {
    printf("%s incorrect, suggestion(s):", input);
    if (pred != NULL) printf(" %s", pred->key);
    if (succ != NULL) printf(" %s", succ->key);
    if (last != NULL && last != pred && last != succ) printf(" %s", last->key);
}        return 0;

}

the functions sometimes work when the string exist in the bst it not it returns garbage without printing anything
the output

   enter your sentence:
aaaaa

-------------------------

Process returned -1073741819 (0xC0000005)   execution time : 4.615 s
Press any key to continue.
  • if (temp != NULL) should be (temp == NULL) – Asphodel May 15 '22 at 20:59
  • Does this answer your question? [Searching for a string in BST fails](https://stackoverflow.com/questions/72249762/searching-for-a-string-in-bst-fails). Please first deal with the answer to your previous question on the same problem. – trincot May 16 '22 at 07:06

0 Answers0