哈夫曼编码C++

哈夫曼编码

// An highlighted block
#include <bits/stdc++.h>
using namespace std;

struct Node{
    int key;
    Node *lchild,*rchild;
    string code="";
    Node(int k){
        key=k;
        lchild=rchild=nullptr;
    }
    Node(int k,Node *l,Node *r){
        key=k;
        lchild=l;
        rchild=r;
    }
    };



struct cmp{
    bool operator()(Node *a,Node *b)
    {
        return a->key>b->key;
    }
};


Node *root;
vector<Node *> nodes;
//构建哈夫曼树
void createHuffman(vector<int> weights) 
{
    //优先队列,用于辅助构建哈夫曼树
    priority_queue<Node*,vector<Node*>,cmp> nodeQueue;
    //构建森林,初始化nodes数组
    for(int i=0; i<weights.size(); i++){
        Node *tm=new Node(weights[i]);
        nodes.push_back(tm);
        nodeQueue.push(tm);
    }
    //主循环,当结点队列只剩一个结点时结束
    while (nodeQueue.size() > 1) {
        //从结点队列选择权值最小的两个结点
        Node *left = (Node *)nodeQueue.top();
        nodeQueue.pop();
        Node *right = (Node *)nodeQueue.top();
        nodeQueue.pop();
        //创建新结点作为两结点的父节点
        Node *parent=new Node(left->key + right->key, left, right);
        nodeQueue.push(parent);
    }
    root = nodeQueue.top();
}
//按照前序遍历输出
void output(Node *head) {
    if(head == nullptr){
        return;
    }
    cout<<head->key<<" ";
    output(head->lchild);
    output(head->rchild);
}

void encode(Node* node, string code){
    if(node == nullptr){
        return;
    }
    node->code = code;
    encode(node->lchild, node->code+"0");
    encode(node->rchild, node->code+"1");
}

string convertHuffmanCode(int index) {
        return nodes[index]->code;
}

int main() {
    vector<char> chars = {'A','B','C','D','E','F'};
    vector<int> weights = {2,3,7,9,18,25};
    createHuffman(weights);
    encode(root,"");
    // output(root);
    for(int i=0; i<chars.size(); i++){
        cout<<chars[i] <<":" << convertHuffmanCode(i)<<endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值