PTA 树种统计

5-12 树种统计   (25分)

随着卫星成像技术的应用,自然资源研究机构可以识别每一棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。

输入格式:

输入首先给出正整数N(\le 10^5105),随后N行,每行给出卫星观测到的一棵树的种类名称。种类名称由不超过30个英文字母和空格组成(大小写不区分)。

输出格式:

按字典序递增输出各种树的种类名称及其所占总数的百分比,其间以空格分隔,保留小数点后4位。

输入样例:

29
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
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow

输出样例:

Ash 13.7931%
Aspen 3.4483%
Basswood 3.4483%
Beech 3.4483%
Black Walnut 3.4483%
Cherry 3.4483%
Cottonwood 3.4483%
Cypress 3.4483%
Gum 3.4483%
Hackberry 3.4483%
Hard Maple 3.4483%
Hickory 3.4483%
Pecan 3.4483%
Poplan 3.4483%
Red Alder 3.4483%
Red Elm 3.4483%
Red Oak 6.8966%
Sassafras 3.4483%
Soft Maple 3.4483%
Sycamore 3.4483%
White Oak 10.3448%
Willow 3.4483%

Yellow Birch 3.4483%

//本质为建树:二叉搜索树
//由此可以看出:二叉搜索树的中序遍历结果为排好序的
#include 
#include 
#include 
using namespace std;
int n;
struct treeNode{
	char data[40];
	int count;
	struct treeNode* left;
	struct treeNode* right;
};
void inTrversalOrder(struct treeNode* binSearchTree)
{
	double rate=(double)binSearchTree->count/n;
	if(binSearchTree==NULL)
		return;
	if(binSearchTree->left)
		inTrversalOrder(binSearchTree->left);
	cout<< binSearchTree->data <<' ';
	printf("%.4f%c\n",rate*100,'%');
	if(binSearchTree->right)
		inTrversalOrder(binSearchTree->right);
	return;
}
struct treeNode* Insert(struct treeNode* binSearchTree,char temp[])
{
	if(binSearchTree==NULL){
		binSearchTree=(struct treeNode*)malloc(sizeof(struct treeNode));
		strcpy(binSearchTree->data,temp);
		binSearchTree->count=1;
		binSearchTree->left=binSearchTree->right=NULL;
		return binSearchTree;	
	}
	int flag=strcmp(temp,binSearchTree->data);
	if(flag>0)
		binSearchTree->right=Insert(binSearchTree->right,temp);
	else if(flag<0)
		binSearchTree->left=Insert(binSearchTree->left,temp);
	else
		binSearchTree->count++;
	return binSearchTree;
}
int main(){	
	char temp[40];
	struct treeNode* binSearchTree=NULL;
	cin>>n;
	getchar();
	for(int i=1;i<=n;i++){
		gets(temp);
		binSearchTree=Insert(binSearchTree,temp);
	}
	postTrversalOrder(binSearchTree);
	return 0;
}


你可能感兴趣的:(PTA数据结构题+大二习题)