利用二叉搜索树来实现排序 BSTree(pku 1002)

来自:http://blog.csdn.net/benny5609/category/334908.aspx 

#include <iostream>

using namespace std;

int flag;

class tNode{
    public:
        tNode();
        tNode(int value);
        int val;
        int counts;
        tNode * lch, * rch;
};
tNode::tNode(){
    val = 0;
    counts = 0;
    lch = rch = NULL;
}
tNode::tNode(int value) {
    val = value;
    counts = 1;
    lch = rch = NULL;
}

class BSTree{
    public:
        BSTree();
        tNode * insert(tNode *);
        void mfs(tNode *);
        tNode * root;
};
BSTree::BSTree(){
    root = NULL;
}
tNode * BSTree::insert(tNode * z) {  //寻找合适的位置来插入
    tNode * y = NULL;
    tNode * x = root;
    while (x!=NULL) {   //寻找合适的插入位置
        y = x;
        if (z->val == x->val) {  //与要插入的元素值相同的元素已经存在
            ++x->counts;
            break;
        } else if (z->val < x->val) {
            x = x->lch;
        } else {
            x = x->rch;
        }
    }
    if (NULL==x) {
        if (NULL==y) root = z;  //之前是一棵空的树
        else {    //插在已经找到的合适的位置
            if (z->val < y->val)
                y->lch = z;
            else
                y->rch = z;
        }
    }
    return z;
}

void BSTree::mfs(tNode * tn) { //具有排序的功能。从二叉树的最左边开始递归遍历整棵树
    if (NULL==tn) return;
    mfs(tn->lch);
    if (tn->counts>1)
 {
        if (!flag)
   flag = 1;
        cout.width(3);
        cout<<tn->val/10000;
        cout<<"-";
        cout.width(4);
        cout<<tn->val%10000;
        cout<<" "<<tn->counts<<endl;
    }
    mfs(tn->rch);
}


int main(){
    int i,N,val;
    char c;
    BSTree * bst = new BSTree();
    flag = 0;
    cin>>N;
    c = cin.get(); // remove '/n'
    for (i=0;i<N;++i) {
        // input
        val = 0;
        while ((c=cin.get())!='/n'){
            if (c>='0' && c<='9')
                val=val*10+c-'0';
            else if (c>='A' && c<'Q')
                val=val*10+(c-'A')/3+2;
            else if (c>'Q' && c<'Z')
                val=val*10+(c-'Q')/3+7;
        }
        bst->insert(new tNode(val));
        // solve
    }
    cout.fill('0');
    bst->mfs(bst->root);
    if (!flag) cout<<"No duplicates. ";
    delete bst;
    return 0;
}

 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值