poj2418 Hardwood Species *

/*
* 二叉查找树练习
* 2418.cpp
*
* Created on: 2011-7-21
* Author:
*/

#include
<cstdio>
#include
<cstring>
using namespace std;

const int maxs = 10000 + 5;
const int ROOT = 0;
struct SData{
char name[35];
int num;
SData
*left, *right;

SData(): num(
0), left(NULL), right(NULL) {}
};

SData
*tree[maxs];
int tot = 0;

void insert(SData *root, char *z){
SData
*y = NULL;
SData
*x = root;

while(x != NULL){
if(strcmp(x->name, z) == 0){
x
->num++;
return;
}

y
= x;
if(strcmp(x->name, z) > 0) x = x->left;
else x = x->right;
}

if(y == NULL){
tree[ROOT]
= new SData;
strcpy(tree[ROOT]
->name, z);
tree[ROOT]
->num++;
}
else if(strcmp(y->name, z) > 0){
y
->left = new SData;
strcpy(y
->left->name, z);
y
->left->num++;
}
else{
y
->right = new SData;
strcpy(y
->right->name, z);
y
->right->num++;
}
}

void inorder_tree_walk(SData *root){
if(root == NULL) return;

inorder_tree_walk(root
->left);
printf(
"%s %.4lf\n", root->name, root->num * 100.0 / tot);
inorder_tree_walk(root
->right);
}

int main(){
char tmp[35];
tree[ROOT]
= NULL;

while(gets(tmp)){
tot
++;
insert(tree[ROOT], tmp);
}

inorder_tree_walk(tree[ROOT]);

return 0;
}
原文地址:https://www.cnblogs.com/longdouhzt/p/2113066.html