c++类实现哈夫曼树权值和
时间: 2023-08-05 07:47:26 浏览: 115
好的,下面是C++类实现哈夫曼树权值和的代码:
```c++
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
class HuffmanTree {
public:
HuffmanTree(int *weights, int size) {
buildHuffmanTree(weights, size);
}
~HuffmanTree() {
deleteTree(root);
}
int getWeightSum() {
return weightSum(root);
}
private:
struct TreeNode {
int weight;
TreeNode *left, *right;
TreeNode(int weight) : weight(weight), left(NULL), right(NULL) {}
};
struct TreeNodeCompare {
bool operator()(const TreeNode *a, const TreeNode *b) {
return a->weight > b->weight;
}
};
TreeNode *root;
void buildHuffmanTree(int *weights, int size) {
priority_queue<TreeNode *, vector<TreeNode *>, TreeNodeCompare> pq;
for (int i = 0; i < size; i++) {
pq.push(new TreeNode(weights[i]));
}
while (pq.size() > 1) {
TreeNode *node1 = pq.top();
pq.pop();
TreeNode *node2 = pq.top();
pq.pop();
TreeNode *node = new TreeNode(node1->weight + node2->weight);
node->left = node1;
node->right = node2;
pq.push(node);
}
root = pq.top();
}
void deleteTree(TreeNode *node) {
if (node == NULL) {
return;
}
deleteTree(node->left);
deleteTree(node->right);
delete node;
}
int weightSum(TreeNode *node) {
if (node == NULL) {
return 0;
}
return node->weight + weightSum(node->left) + weightSum(node->right);
}
};
int main() {
int weights[] = {10, 15, 12, 3, 4, 13, 1};
int size = sizeof(weights) / sizeof(weights[0]);
HuffmanTree tree(weights, size);
cout << "Weight sum of Huffman tree: " << tree.getWeightSum() << endl;
return 0;
}
```
该代码使用了C++类来实现哈夫曼树的构建和权值和的计算。在构造函数中,我们使用了STL中的优先队列来构建哈夫曼树。在析构函数中,我们使用递归的方式来释放哈夫曼树的内存。在计算权值和的函数中,我们使用递归的方式来遍历哈夫曼树,并计算所有节点的权值之和。你可以将weights数组替换为自己的数据,然后运行该代码,即可输出对应的哈夫曼树权值和。
阅读全文