7-24 树种统计(25 分)(二叉排序的应用)

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

输入格式:

输入首先给出正整数N(105​​),随后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%
 
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 
 5 typedef struct TNode *Position;
 6 typedef Position BinTree;
 7 struct TNode
 8 {
 9     char data[35];
10     BinTree left;
11     BinTree right;
12     int count;
13 };
14 BinTree Insert( BinTree BT , char name[]);
15 void Print( BinTree BT , int n);
16 int main()
17 {
18     int n;
19     int i;
20     BinTree BT = NULL;
21 
22     scanf("%d",&n);
23     getchar();
24     for( i=0; i<n; i++){
25         char name[35];
26         gets(name);
27         BT = Insert( BT,name);
28     }
29     Print( BT ,n);
30 
31     return 0;
32 }
33 
34 
35 BinTree Insert( BinTree BT , char name[])
36 {
37     if( !BT ){
38         BT = ( BinTree )malloc(sizeof(struct TNode));
39         strcpy(BT->data,name);
40         BT->count=1;
41         BT->left = BT->right =NULL;
42     }
43     else{
44         int a = strcmp( BT->data,name);
45         if( a<0 )  BT->right = Insert( BT->right,name);
46 
47         else if( a>0 ) BT->left=Insert( BT->left,name);
48         else BT->count++;
49     }
50     return BT;
51 }
52 
53 void Print( BinTree BT , int n)
54 {
55     if( !BT ) return;
56     else{
57         Print( BT->left,n);
58         printf("%s ",BT->data);
59         printf("%.4f%%\n",(double)BT->count/n*100.0);
60         Print( BT->right,n);
61     }
62 }

 

posted @ 2018-02-03 09:17  yuxiaoba  阅读(1139)  评论(0编辑  收藏  举报