题目
解答
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct BiTNode{
char word[255];
int cnt;
struct BiTNode* lchild;
struct BiTNode* rchild;
}BiTNode,* BiTree;
int sum=0;
int InsertBiTree(BiTree *T, char word[]){
if(!(*T)){
*T = (BiTree)malloc(sizeof(BiTNode));
if(!(*T))
exit(0);
(*T)->cnt =1;
strcpy((*T)->word ,word);
(*T)->lchild = (*T)->rchild =NULL;
}
else if(strcmp((*T)->word ,word)<0)
InsertBiTree(&(*T)->rchild , word);
else if(strcmp((*T)->word ,word)>0)
InsertBiTree(&(*T)->lchild ,word);
else
(*T)->cnt++;
}
void InOrderTraverse(BiTNode *T, int sum){
if(T){
InOrderTraverse(T->lchild ,sum);
printf("%s\t%d/%d\n",T->word ,T->cnt ,sum);
InOrderTraverse(T->rchild ,sum);
}
}
int main(){
FILE *fp;
char word[255];
BiTree T;
T=NULL;
fp = fopen("article.txt", "r");
while(fscanf(fp, "%s", word)!=EOF){
InsertBiTree(&T, word);
++sum;
}
printf("总共有%d个单词\n",sum);
InOrderTraverse(T,sum);
fclose(fp);
return 0;
}