题目的大致意思是:记录每个字符串出现的次数,并输出字符串、字符串出现的次数与所有字符串总数的比例*100;
采用了二插查找树的方法
C语言实现:
#include<stdio.h>
#include<stdlib.h>
#include
typedef char KeyType[30];
typedef struct Node
{
KeyType key;//关键字
int times;
struct Node * left; //左孩子指针
struct Node * right; //右孩子指针
struct Node * parent; //指向父节点指针
}Node,*PNode;
//往二叉查找树中插入结点
//插入的话,可能要改变根结点的地址,所以传的是二级指针
PNode init(KeyType key)
{
PNode p=(PNode)malloc(sizeof(Node));
strcpy(p->key,key);
p->left=p->right=p->parent=NULL;
p->times=1;
return p;
}
void insert(PNode * root,KeyType key)
{
//空树时,直接作为根结点
if((*root)==NULL){
PNode p=init(key);
*root=p;
return;
}
//如果树中已存在该节点,则times值加1
if(strcmp((*root)->key , key)==0)
{
(*root)->times+=1;
return;
}
//插入到当前结点(*root)的左孩子
if((*root)->left == NULL && strcmp((*root)->key , key)>0){
PNode p=init(key);
p->parent=(*root);
(*root)->left=p;
return;
}
//插入到当前结点(*root)的右孩子
if((*root)->right == NULL && strcmp((*root)->key , key)<0){
PNode p=init(key);
p->parent=(*root);
(*root)->right=p;
return;
}
if(strcmp((*root)->key , key)>0)
inseart(&(*root)->left,key);
else if(strcmp((*root)->key , key)<0)
inseart(&(*root)->right,key);
else
return;
}
//查找最小关键字,空树时返回NULL
PNode searchMin(PNode root)
{
if(root == NULL)
return NULL;
if(root->left == NULL)
return root;
else //一直往左孩子找,直到没有左孩子的结点
return searchMin(root->left);
}
//查找某个结点的后继
PNode searchSuccessor(PNode p)
{
//空树
if(p==NULL)
return p;
//有右子树、右子树中最小的那个
if(p->right)
return searchMin(p->right);
//无右子树,查找某个结点的左子树遍历完了
else{
if(p->parent == NULL)
return NULL;
//向上寻找后继
while(p){
if(p->parent==NULL)
break;
if(p->parent->left == p)
break;
p=p->parent;
}
return p->parent;
}
}
//二叉树的遍历
void middleOrder(PNode min)
{
if(min)
{
printf("%s\t",min->key);
printf("%.4lf",((double)min->times*100/29.00));
printf("\n");
middleOrder(searchSuccessor(min));
}
else
return;
}
//创建一棵二叉查找树
void create(PNode* root,KeyType *keyArray,int length)
{
int i;
for(i=0;i
insert(root,keyArray[i]);
}
int main(void)
{
char input[29][30]={"Red Alder","Ash","Aspen","Basswood","Ash","Beech","Yellow Birch","Ash","Cherry","Cottonwood",
"Ash","Cypress","Red Elm","Gum","Hackberry","White Oak","Hickory","Pecan","Hard Maple","White Oak",
"Soft Maple","Red Oak","Red Oak","WhiteOak","Poplan","Sassafras","Sycamore","Black Walnut","Willow"};
PNode root=NULL;
create(&root,input,29);
middleOrder(searchMin(root));
getchar();
return 1;
}