2013-08-30 97 views
-2

我該如何開發一個程序,該程序從文本文件中讀取單詞並使用這些單詞創建按字母順序排序的二叉搜索樹?這裏是我的代碼c中按字母順序排序的二叉搜索樹?

#include "stdio.h" 
#include "stdlib.h" 
#include "string.h" 

struct treeNode { 
     char data[20]; 
     int count; 
     struct treeNode *leftPtr, *rightPtr; 
}; 

int number; 

typedef struct treeNode TreeNode; 
typedef TreeNode *TreeNodePtr; 

void insertNode (TreeNodePtr *treePtr,char word[]); 
void alphabetic(TreeNodePtr treePtr); 




int main(){ 

    /*reading strings from the file and add them to the tree*/ 

    char first[20]; 
    FILE *fp1; 
    TreeNodePtr rootPtr=NULL; 
    int c; 
    fp1=fopen("output.txt","r"); 
    do{ 
     c=fscanf(fp1,"%s",first); 
     insertNode(&rootPtr,first); 




    }while(c!=EOF); 


    fclose(fp1); 

    alphabetic(rootPtr); 

    system("PAUSE"); 

} 

/*for adding nodes to tree*/ 

void insertNode (TreeNodePtr *treePtr,char word[20]){ 
    TreeNode *temp = NULL; 
    if(*treePtr == NULL) 
    { 
     temp = (TreeNode *)malloc(sizeof(TreeNode)); 
     temp->leftPtr = NULL; 
     temp->rightPtr = NULL; 
     temp->data[20] = word[20]; 
     *treePtr = temp; 

    } 
    else if(strcmp(word,(*treePtr)->data)<0){ 


     insertNode(&((*treePtr)->leftPtr),word); 
    } 
    else if (strcmp(word,(*treePtr)->data)>0){ 


     insertNode(&((*treePtr)->rightPtr),word); 
    } 
    else{ 
     number++; 
    } 
} 

/*for sorting alphabetically*/ 
void alphabetic(TreeNodePtr treePtr){ 
    if(treePtr!=NULL){ 
     alphabetic(treePtr->leftPtr); 
     printf("%3d\n",treePtr->leftPtr); 
     alphabetic(treePtr->rightPtr); 
    } 
} 

當我有一個.txt包括4個單詞我的程序寫入四個0的輸出。

+0

什麼是typedefing'Tre eNodePtr'?你沒有保存任何鍵入,也沒有抽象出它是一個指針的事實。我會擺脫typedef。 – idoby

+0

你的函數「字母」不排序任何東西,它遍歷樹。出於某種原因,將指針顯示爲整數。 – Medinoc

回答

2

此行是錯誤的:

temp->data[20] = word[20]; 

它複製某一個字符一個無效的位置到另一個位置。

將其更改爲:

strcpy(temp->data, word); 

因爲要複製的字符串。

而且這一行看起來錯誤:

printf("%3d\n",treePtr->leftPtr); 

我猜你想在這裏打印data字符串的內容,所以它應該是:

printf("%s\n", treePtr->data); 

,或者如果你想要的整數count元素它將是:

printf("%d\n", treePtr->count); 
+0

感謝您的幫助,它工作:)但我必須計算一個詞在二叉樹中存在多少次,我不能這樣做,我該怎麼做? – user2733502

+0

@ user2733502你總是可以遍歷樹並保留一個計數器。 –