poj2418 二叉排序树

/**
 * 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值