哈夫曼编码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;
}

你可能感兴趣的:(算法)