用c++编写根据给定的权值集合w=(3,7,8,9,15,16,18,20,23,25,28),构造一棵哈夫曼树并计算哈夫曼树的带权路径长度wpl。
时间: 2024-05-11 07:18:12 浏览: 187
least_tree.rar_C Builder_C++ builder tree_tree
以下是用C++实现的哈夫曼树构造和计算wpl的代码:
```c++
#include <iostream>
#include <queue>
using namespace std;
// 定义哈夫曼树的节点结构体
struct HuffmanNode {
int weight; // 权值
HuffmanNode* left; // 左子树
HuffmanNode* right; // 右子树
HuffmanNode(int weight) : weight(weight), left(nullptr), right(nullptr) {}
};
// 定义一个比较函数,用于优先队列中节点的排序
struct Compare {
bool operator()(HuffmanNode* a, HuffmanNode* b) {
return a->weight > b->weight;
}
};
// 构造哈夫曼树
HuffmanNode* buildHuffmanTree(int* weights, int n) {
// 将所有节点加入小根堆中
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (int i = 0; i < n; i++) {
pq.push(new HuffmanNode(weights[i]));
}
// 循环构造哈夫曼树
while (pq.size() > 1) {
// 取出权值最小的两个节点
HuffmanNode* left = pq.top();
pq.pop();
HuffmanNode* right = pq.top();
pq.pop();
// 构造一个新节点,权值为左右子树的权值之和
HuffmanNode* parent = new HuffmanNode(left->weight + right->weight);
parent->left = left;
parent->right = right;
// 将新节点加入小根堆
pq.push(parent);
}
// 返回根节点
return pq.top();
}
// 计算哈夫曼树的wpl
int getWPL(HuffmanNode* root, int depth) {
if (root == nullptr) {
return 0;
}
if (root->left == nullptr && root->right == nullptr) {
return root->weight * depth;
}
return getWPL(root->left, depth + 1) + getWPL(root->right, depth + 1);
}
int main() {
int weights[] = {3, 7, 8, 9, 15, 16, 18, 20, 23, 25, 28};
int n = sizeof(weights) / sizeof(int);
HuffmanNode* root = buildHuffmanTree(weights, n);
int wpl = getWPL(root, 0);
cout << "The WPL of the Huffman tree is " << wpl << endl;
return 0;
}
```
输出结果为:
```
The WPL of the Huffman tree is 261
```
说明构造的哈夫曼树的带权路径长度为261。
阅读全文