2014-11-22 124 views
-1

我想在二叉搜索树中搜索一个单词。这是我的代码。但它有运行时错误。如何在二叉搜索树中搜索单词?

struct node { 
int id; 
char text[100]; 
strcut node *right; 
struct node *left; 
} 


int main(){ 

// reading fles from the folder. The folder's name is Texts . 
if((dir = opendir("C:\\Texts\\")) != NULL){ 
while((ent = readdir(dir)) != NULL){ 
char k[100],l[100],*w; 
char b[100]; 
char a[100]="C:\\Texts\\"; 
strcpy(b,folder->d_name); 
file=fopen((strcat(a,b)),"r"); 
while(!feof(file)){ 
fgets(l,sizeof(l),file); 
printf("%s",l); } 
} 
void listWord(node *tree,char word[]){ 
node * g, * h; 
g=tree; 
    if(g==NULL){ 
    printf("list is empty"); 
    } 
    else{ 
     while(g!=NULL){ 
      if(strstr(g->text,word)!=NULL){ 
      printf(" specific word %s: \n",word); 
      printf("\n\t\t id is :%d ",g->id); 
     } 
    listWord(g->left,word); 
    listWord(g->right,word); 
    } 
} 

它不起作用:/我该如何解决它? P.S:给出的frm用户和结构节点树有左,右,id,文本。

+1

你能粘贴错误吗? – theharshest 2014-11-22 20:57:21

+2

主要问题是你不更新循环内的循环变量'g',所以它将是无限的。 – 2014-11-22 20:59:10

+0

错误是运行时错误@theharshest – elminaa 2014-11-22 21:02:21

回答

0

你必须走整个树,因为你没有通过id搜索,但你似乎已经意识到这一点。为了使用递归遍历树,在左子树上递归调用您的函数,处理当前节点,然后递归调用右子树上的函数(适当地检查NULL)。例如:

void listWord(node *tree, char *word) 
{ 
    if (tree) { 
     /* If tree is not NULL... */ 

     /* recursively process left subtree if present.. */ 
     if (tree->left) 
      listWord(tree->left, word); 

     /* then check the current node.. */ 
     if (strstr(tree->text, word)) { 
      printf(" specific word %s: \n", word); 
      printf("\n\t\t id is :%d ", tree->id); 
     } 

     /* then recursively process the right subtree if present. */ 
     if (tree->right) 
      listWord(tree->right, word); 
    } else 
     printf("list is empty"); 
} 
+0

谢谢,它是非常有用的代码。但是我仍然有时间错误。树的文本来自文件夹..我打开文件夹并阅读它们。当我读取文件夹时可能会出现一些错误:/ – elminaa 2014-11-22 21:54:57

+0

@elminaa什么*都是错误? ((dir = opendir(“C:\\ Texts \\”))!= NULL) – Dmitri 2014-11-22 22:04:04

+0

例如,当我编写Love时,程序返回运行时错误 – elminaa 2014-11-22 22:05:50