您的位置:首页 > 其它

poj2418 二叉排序树

2014-03-18 00:37 176 查看
/**
* poj2418 二叉排序树
* 这道题目可以用二叉排序树来做,也可以用map来做,为了学习,这里我就用了二叉排序树的做法
* 点1:在读取字符串的时候,可以使用下面使用的正则方法,%开启正则,[]指定读取数据的格式,^\n指读取\n之前的数据,即一行,30是指读取的最大长度
* 而另一种方法则是使用gets(tree_name)函数,直接读取一行,更为简洁
* 点2:二叉排序树的使用
* 插入时,将键值(字符串)从树根开始自上而下比较,如果比叶子小,就继续跟左子树根比较,否则跟右子树根比较,直到进入了某个叶子节点,将新节点放置在该位置即可
* 遍历时使用中序遍历,先遍历左子树,然后显示树根,然后遍历右子树
* 由于本题的特殊性,那么如果某次比较结果相等,那就可以中止比较,增加计数就可以了
*/
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;
const int MAX_NUM = 10001;
struct node{
string name;
int count;
node *lchild,*rchild;
node(char* s) : name(s),count(1),lchild(NULL),rchild(NULL){;}
};

void insert(node*& root,char* s){
if(root == NULL){
root = new node(s);
return;
}

node *self=root,*father=root;
int cmpres;

while(self!=NULL){
cmpres = strcmp(s,self->name.c_str());
if(cmpres == 0){
self->count++;
return;
}
father = self;
self = (cmpres > 0)? father->rchild : father->lchild;
}

self = new node(s);
if(cmpres > 0){
father -> rchild = self;
}
else if(cmpres < 0){
father -> lchild = self;
}
}

void print(const node* p,const int count){
if(p!=NULL){
print(p->lchild,count);
printf("%s %.4f\n",p->name.c_str(), 100.0 * p->count / count);
print(p->rchild,count);
}
}

int main(){
char tree_name[32],tmpc;
node* root=NULL;
int count=0;
while(scanf("%30[^\n]",tree_name) != EOF){
getchar();
insert(root,tree_name);
++count;
}

print(root,count);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: