-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpp
108 lines (93 loc) · 1.78 KB
/
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define M 5000
typedef struct node
{
int count;
char word[26];
struct node *lchild, *rchild;
}BTNode, *BTREE;
int times = 0;
int get_word(char *temp_word, FILE *in);
BTREE insert(BTREE T, char temp_word[]);
void inorder(BTREE root);
int main()
{
char temp_word[26] = {0};
FILE *in;
int i,j;
if( (in = fopen("article.txt", "r")) == NULL )
printf("No such file!\n");
BTREE root = NULL;
while( !feof(in) )
{
char temp_word[26] = {0};
get_word(temp_word,in);
root = insert(root, temp_word);
}
printf("%s ", root->word);
if(root->rchild != NULL && root->rchild->rchild == NULL)
printf("%s\n", root->rchild->word );
else
printf("%s ", root->rchild->word );
if(root->rchild->rchild != NULL)
printf("%s\n", root->rchild->rchild->word);
inorder(root);
return 0;
}
int get_word(char *temp_word, FILE *in)
{
int i = 0;
char temp = '0';
temp = fgetc(in);
while( !isalpha(temp) )
{
temp = fgetc(in);
if(temp==EOF)
return 1;
}
while(isalpha(temp) && !isspace(temp) )
{
temp = tolower(temp);
temp_word[i] = temp;
i++;
temp = fgetc(in);
}
return 0;
}
BTREE insert(BTREE p, char temp_word[])
{
int cond;
if(p == NULL)
{
p = (BTREE)malloc(sizeof(BTNode));
strcpy(p->word, temp_word);
p->count = 1;
p->lchild = p->rchild = NULL;
}
else if( (cond = strcmp(temp_word, p->word)) == 0)
{
p->count++;
}
else if( cond<0 )
{
p->lchild = insert(p->lchild, temp_word);
}
else
{
p->rchild = insert(p->rchild, temp_word);
}
return (p);
}
void inorder(BTREE T)
{
if(T!= NULL)
{
inorder(T->lchild);
if( strlen(T->word) >0 )
printf("%s %d\n", T->word, T->count);
inorder(T->rchild);
}
}