您的位置:首页 > 其它

poj-2418 Hardwood Species *

2011-07-21 17:07 337 查看
/*
* 二叉查找树练习
* 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: