2014-11-22 127 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