数据结构------哈夫曼树与哈弗曼编码实现(C/C++)

代码

#include <map>
#include <vector>
#include "iostream"
#include <algorithm>


using namespace std;


typedef char DataType;
typedef struct Node {
    DataType data;
    int weight;             // 权重
    struct Node* left;
    struct Node* right;
}Node;


void initialHuffmanTree(vector<Node*>& vector);
bool compare(Node* a, Node* b);
void printHuffmanCode(Node *&pNode, string codeStr);
Node *createHuffmanTree(vector<Node*>& nodeVec);


int main() {

    // 初始化
    vector<Node*> nodeVec;
    initialHuffmanTree(nodeVec);


    /*for (int i = 0; i < nodeVec.size(); ++i) {
        cout << nodeVec[i]->data << "===" << nodeVec[i]->weight << endl;
    }*/

    // 构建哈夫曼树
    Node* huffmanTree = createHuffmanTree(nodeVec);


    /*for (int i = 0; i < nodeVec.size(); ++i) {
        cout << nodeVec[i]->data << "===" << nodeVec[i]->weight << endl;
    }*/

    // 打印哈夫曼编码
    printHuffmanCode(huffmanTree, "");


    return 0;
}

/**
 * 构建哈夫曼树
 * @param nodeVec
 * @return
 */
Node *createHuffmanTree(vector<Node*>& nodeVec) {
    int index = 0;
    while (index != nodeVec.size()-1) {
        // 依据权重值排序
        sort(nodeVec.begin() + index, nodeVec.end(), compare);

        // 新建父结点,指向当前最小权重的两个节点
        Node* temp = (Node*)malloc(sizeof(Node));
        temp->data = '#';
        temp->weight = nodeVec[index]->weight + nodeVec[index + 1]->weight;
        temp->left = nodeVec[index];
        temp->right = nodeVec[index + 1];

        // 父节点进入vector参与排序
        nodeVec.push_back(temp);
        index += 2;
    }

    // 返回树的根节点
    return nodeVec[nodeVec.size() - 1];
}

/**
 * 打印哈夫曼编码, 递归
 * @param pNode
 * @param codeStr
 */
void printHuffmanCode(Node *&pNode, string codeStr) {
    if (pNode->left == nullptr || pNode->right == nullptr) {
        cout<<pNode->data << " === " << codeStr << endl;
        return;
    }

    printHuffmanCode(pNode->left, codeStr + '0');
    printHuffmanCode(pNode->right, codeStr + '1');
}

bool compare(Node* a, Node* b) {
    return a->weight < b->weight;
}

/**
 * 接收数据
 * @param vector
 */
void initialHuffmanTree(vector<Node*>& vector) {
    char c;
    int weight;
    while (cin >> c >> weight && c != '#') {
        Node* temp = (Node*)malloc(sizeof(Node));
        temp->data = c;
        temp->weight = weight;
        temp->left = temp->right = nullptr;
        vector.push_back(temp);
    }
}

//A 27 B 8 C 15 D 15 E 30 F 5 # 0

结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值