/**
* 实验题目:
* 统计一个字符串中出现的字符及其次数
* 实验目的:
* 掌握二叉排序树的构造过程及其算法设计
* 实验内容:
* 设计程序,读入一个字符串,统计该字符串中每个出现的字符及其
* 次数,然后按字符的ASCII编码顺序输出结果。
* 要求用一颗二叉排序树来保存处理结果,每个结点包含四个域,格式为:
* 字符
* 该字符出现的次数
* 指向ASCII码值小于该字符的左子树指针
* 指向ASCII码值大于该字符的右子树指针
*/
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAX_WORD (100)
typedef struct tnode
{
char ch; // 字符
int cnt; // 出现次数
struct tnode *lchild; // 左指针
struct tnode *rchild; // 右指针
}BSTNode; // 结点类型
/*-----------------采用递归方式向二叉排序树bst中插入一个字符----------------*/
static void create_bst(BSTNode *&bt, char ch) // 指针的引用
{
if(bt == NULL) // bt为空,则建立一个新结点
{
bt = (BSTNode *)malloc(sizeof(BSTNode));
bt->ch = ch;
bt->cnt = 1;
bt->lchild = bt->rchild = NULL;
}
else if(ch == bt->ch)
bt->cnt++;
else if(ch < bt->ch)
create_bst(bt->lchild, ch);
else
create_bst(bt->rchild, ch);
}
/*-----------------中序遍历二叉排序树bst----------------*/
static void inorder(BSTNode *bt)
{
if(bt != NULL)
{
inorder(bt->lchild); // 中序遍历左子树
printf(" %c(%d)\n", bt->ch, bt->cnt); // 访问根结点
inorder(bt->rchild); // 中序遍历右子树
}
}
/*-----------------销毁二叉排序树bst----------------*/
static void destroy_bst(BSTNode *bt)
{
if(bt != NULL)
{
destroy_bst(bt->lchild);
destroy_bst(bt->rchild);
free(bt);
}
}
int main(int argc, char *argv[])
{
BSTNode *bt = NULL;
int i = 0;
char str[MAX_WORD];
printf("输入字符串:");
gets(str);
while(str[i] != '\0')
{
create_bst(bt, str[i]);
i++;
}
printf("字符及出现次数:\n");
inorder(bt);
printf("\n");
destroy_bst(bt);
return 0;
}
测试结果:
输入字符串:Good Bye!
字符及出现次数:
(1)
!(1)
B(1)
G(1)
d(1)
e(1)
o(2)
y(1)