代码解读之哈夫曼树

代码非原创 单纯作为笔记便于复习

代码 

#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <cstdio>
#include <algorithm>

using namespace std;
const int maxn = 27;
int rec[maxn];//下标26个大写字母0-26,rec存储各字母权重
struct tree
{
    char ch;//大写字母
    int num;//权重即出现次数
    tree * lchild;//左孩子
    tree * rchild;//右孩子

    tree(char cc = '@',int nn = 0):ch(cc),num(nn),lchild(NULL),rchild(NULL) {}
};

struct cmp//函数对象,作为比较函数用于优先队列
{
    bool operator()(const tree *a,const tree* b)const
    {
        return a->num > b->num;
    }
};

priority_queue<tree*,vector<tree*>,cmp> qu;

void createTree()
{
    for(int i = 0  ; i < 26 ; i++)
    {
        if(rec[i])
        {
            tree * node = new tree;
            node->num = rec[i];
            node->ch = (char)(i+'A');
            qu.push(node);
        }
    }

    while(qu.size() > 1)
    {
        tree * f = qu.top();
        qu.pop();
        tree * s = qu.top();
        qu.pop();

        tree * tmp = new tree();//ch='@'
        tmp->num = f->num + s->num;
        tmp->lchild = f,tmp->rchild = s;
        qu.push(tmp);
    }
}
struct printTree
{
    int num;
    char ch;
    string code;
    ~printTree() {}
};
vector<printTree> PT;
void print(tree* root, string res)
{
    if(root == NULL)
        return ;
    if(root->ch != '@')
    {
        printTree pt;
        pt.num = root->num;
        pt.ch = root->ch;
        pt.code = res;
        PT.push_back(pt);
        return;
    }
    print(root->lchild,res+"0");
    print(root->rchild,res+"1");
    delete root->lchild;
    delete root->rchild;
}
bool cmp2(const printTree & a,const printTree & b)
{
    return a.num > b.num;
}
int main()
{
//    freopen("in.txt","r",stdin);
    for(int i = 0 ; i < maxn ; i++)
        rec[i] = 0;
    int num;
    cin >> num;
    char ch;
    for(int i = 0 ; i < num ; i++)
    {
        cin >> ch;
        rec[ch-'A']++;
    }
    createTree();
    tree * root = qu.top();
    qu.pop();
    print(root,"");
    sort(PT.begin(),PT.end(),cmp2);
    for(size_t i = 0 ; i < PT.size(); i++)
    {
        cout << PT[i].ch << " " << PT[i].num << " " << PT[i].code << endl;
    }
    return 0;
}

图解

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值