2013-08-30 68 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你总是可以遍历树并保留一个计数器。 –