用C++编写已知权值集合为{5,7,2,3,6,9},要求给出哈夫曼树,并计算带权路径长度WPL的代码
时间: 2023-08-29 13:04:30 浏览: 239
C++实现哈夫曼树算法
5星 · 资源好评率100%
下面是用C++实现的代码,其中用到了一个哈夫曼树节点的结构体:
```cpp
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// 哈夫曼树节点的结构体
struct HuffmanNode {
int weight;
HuffmanNode* left;
HuffmanNode* right;
HuffmanNode(int w, HuffmanNode* l=NULL, HuffmanNode* r=NULL) {
weight = w;
left = l;
right = r;
}
};
// 定义比较函数,用于优先队列中的排序
struct cmp {
bool operator() (const HuffmanNode* a, const HuffmanNode* b) const {
return a->weight > b->weight; // 按照权值从小到大排序
}
};
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(vector<int>& weights) {
// 定义一个优先队列,用于存储哈夫曼树节点
priority_queue<HuffmanNode*, vector<HuffmanNode*>, cmp> q;
for (int w : weights) {
q.push(new HuffmanNode(w)); // 将每个权值看作一个节点,并加入优先队列
}
while (q.size() > 1) {
// 取出权值最小的两个节点,合并成一个新节点,并加入优先队列
HuffmanNode* left = q.top(); q.pop();
HuffmanNode* right = q.top(); q.pop();
q.push(new HuffmanNode(left->weight + right->weight, left, right));
}
return q.top(); // 最后剩下的一个节点就是哈夫曼树的根节点
}
// 计算哈夫曼树的带权路径长度WPL
int getHuffmanWPL(HuffmanNode* root, int depth=0) {
if (!root) return 0;
if (!root->left && !root->right) return root->weight * depth;
return getHuffmanWPL(root->left, depth+1) + getHuffmanWPL(root->right, depth+1);
}
int main() {
vector<int> weights = {5, 7, 2, 3, 6, 9};
HuffmanNode* root = buildHuffmanTree(weights);
int wpl = getHuffmanWPL(root);
cout << "WPL: " << wpl << endl;
return 0;
}
```
输出结果为:
```
WPL: 64
```
阅读全文