利用二叉排序树解决词频统计问题
【易错点】
1.在插入之前要判断是否为单词
2.root和count都要初始化
【代码】
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxSize 100
typedef struct BTNode
{
char data[maxSize];
struct BTNode* lchild, *rchld;
int count;//单词在字符串中出现的次数
}BTNode;
//二叉排序树插入算法
BTNode* Insert(BTNode* root, char word[])
{
if (root == NULL)
{
root = (BTNode*)malloc(sizeof(BTNode));
root->lchild = root->rchld = NULL;
root->count = 1;
strcpy(root->data, word);
}
else if (strcmp(root->data, word) > 0)
{
root->lchild = Insert(root->lchild, word);
}
else if (strcmp(root->data, word) == 0)
{
(root->count)++;
}
else
{
root->rchld = Insert(root->rchld, word);
}
return root;
}
//前序遍历输出统计的单词次数
void pre(BTNode*bt)
{
if (bt)
{
printf("%s:%d\n", bt->data, bt->count);
pre(bt->lchild);
pre(bt->rchld);
}
}
//判断是否为字母,是就返回1,不是返回0
int IsAlpha(char ch)
{
if ((ch >= 'A'&& ch <= 'Z') || (ch >= 'a'&&ch <= 'z'))
return 1;
return 0;
}
int main()
{
//输入字符串
char s[10000];
char c;
int i;
BTNode* root;
root = NULL;
i = 0;
while ((c = getchar()) != '\n')
{
s[i++] = c;
}
s[i] = '\0';
//构建二叉排序树
char word[maxSize];
int j;
i = 0;
while (s[i] != '\0')
{
j = 0;
//判断是否为单词
while (IsAlpha(s[i]))
{
word[j] = s[i];
j++;
i++;
}
word[j] = '\0';
//如果是单词则插入
if (word[0] != '\0')
{
root = Insert(root, word);
}
//不是单词则跳过
while (!IsAlpha(s[i]))
{
if (s[i] == '\0')
break;
i++;
}
}
pre(root);
return 0;
}
【测试】
利用自定义结构体解决