记一次词频统计--用二叉搜索树实现

#include<bits/stdc++.h>
using namespace std;
//Data stored in the node type

struct WordCount
{

    string word;

    int count;
};

//Node type:

struct TreeNode
{

    WordCount info;

    TreeNode * left;

    TreeNode * right;

};

// Two function's prototype

// Increments the frequency count if the string is in the tree

// or inserts the string if it is not there.

void Insert(TreeNode*&rt, string tmp)
{
    if(!rt)
    {
        rt = new TreeNode;
        rt->info.word = tmp;
        rt->info.count = 1;
        rt->left = rt->right = NULL;
        return ;
    }
    else if(tmp==rt->info.word)
    {
        rt->info.count++;
    }
    else if(tmp<rt->info.word)
    {
        Insert(rt->left,tmp);
    }
    else
    {
        Insert(rt->right,tmp);
    }

}


// Prints the words in the tree and their frequency counts.

void PrintTree(TreeNode* rt, ofstream& outfile)
{

    if(rt!=NULL)
    {
       // cout<<rt->info.word<<" "<<rt->info.count<<endl;
        outfile<<rt->info.word<<" "<<rt->info.count<<endl;


        PrintTree(rt->left,outfile);
        PrintTree(rt->right,outfile);
    }

}

//Start your main function and the definitions of above two functions.
int main()
{
    ifstream infile;
    ofstream outfile;
    string in_name,out_name;
    cout<<"please input the name of infile"<<endl;
    cin>>in_name;
    infile.open(in_name.c_str());
    string tmp;
    TreeNode * root  = NULL;
    while(infile>>tmp)
    {
        if(tmp=="")continue;
        //    cout<<tmp<<endl;
        int len = tmp.size();
        if(len<3)continue;
        if(tmp[len-1]>='a'&&tmp[len-1]<='z')
        {
            Insert(root,tmp);
        }
        else if(tmp[len-1]>='A'&&tmp[len-1]<='Z')
        {
            Insert(root,tmp);
        }
        else if(tmp[len-1]>='0'&&tmp[len-1]<='9')
        {
            Insert(root,tmp);
        }
        else
        {
            string hh = "";
            for(int i=0; i<len-1; i++)
            {
                hh+=tmp[i];
            }
            Insert(root,hh);

        }
    }
    infile.close();
    cout<<"please input the name of outfile"<<endl;
    cin>>out_name;
    outfile.open(out_name.c_str());
    PrintTree(root,outfile);
    outfile.close();
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值