想看更多的解题报告: http://blog.csdn.net/wangjian8006/article/details/7870410
转载请注明出处:http://blog.csdn.net/wangjian8006
题目大意:
输入若干行英文,每行代表一棵树,英文中可能有空格与重复,并且不超过30个字符,说不超过10,000种树,和不超过1,000,000棵树
要求输出用字典序输出,并且统计那棵树出现的百分比例,并且保留四位小数
解题思路:
输入若干行,用二叉排序树的形式插入到一棵树中,并统计出现的次数
代码:
/* 二叉排序树*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char a[31];
typedef struct nod{
char b[31];
int num;
struct nod *lchild,*rchild;
}node;
node *bt;
int count = 0;
void Insert();
void print(node *p);
int main(){
bt = NULL;
while(gets(a)!=NULL){
count++;
Insert();
}
print(bt);
return 0;
}
void Insert(){
node *p = bt;
node *q = NULL;//q在这里有2个作用 ,太巧妙了
int flag = 0;
while(p != NULL){
if(!strcmp(a,p->b)){
p->num++;
return;
}
q = p;
p = (strcmp(a,p->b)>0)?p->rchild:p->lchild;
flag = 1;
}
if(q == NULL){//q的第1个作用:判断是否为空树
bt = (node *)malloc(sizeof(struct nod));
strcpy(bt->b,a);
bt->num = 1;
bt->lchild = NULL;
bt->rchild = NULL;
}else{
if(flag){
p = (node *)malloc(sizeof(struct nod));
strcpy(p->b,a);
p->num = 1;
p->lchild = NULL;
p->rchild = NULL;
}
if(strcmp(q->b,a) > 0){//q的第2个作用:记录p结点,以便能使插入的结点连接到树中
q->lchild = p;
}else{
q->rchild = p;
}
}
}
void print(node *p){
if(p != NULL){
print(p->lchild);
printf("%s %.4f\n",p->b,100.0*p->num/count);//注意这里*100.0
print(p->rchild);
}
}