请以这个结构为基础帮我用c++语言实现赫夫曼树以及赫夫曼编码:typedef struct { int weight; int parent, lchild, rchild; }HTNode, * HuffmanTree; typedef char** HuffmanCode;
时间: 2023-08-08 21:06:55 浏览: 103
好的,以下是用 C++ 实现赫夫曼树和赫夫曼编码的代码:
```c++
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
typedef struct {
int weight; // 权重
int parent, lchild, rchild; // 父节点,左子节点,右子节点的下标
} HTNode, * HuffmanTree;
typedef char** HuffmanCode;
void CreateHuffmanTree(HuffmanTree& HT, int n) {
HT = new HTNode[2 * n - 1];
for (int i = 0; i < n; i++) {
cin >> HT[i].weight;
HT[i].parent = -1;
HT[i].lchild = -1;
HT[i].rchild = -1;
}
for (int i = n; i < 2 * n - 1; i++) {
int min1 = INT_MAX, min2 = INT_MAX;
int min1_idx = -1, min2_idx = -1;
for (int j = 0; j < i; j++) {
if (HT[j].parent == -1 && HT[j].weight < min1) {
min2 = min1;
min2_idx = min1_idx;
min1 = HT[j].weight;
min1_idx = j;
} else if (HT[j].parent == -1 && HT[j].weight < min2) {
min2 = HT[j].weight;
min2_idx = j;
}
}
HT[i].weight = min1 + min2;
HT[i].lchild = min1_idx;
HT[i].rchild = min2_idx;
HT[min1_idx].parent = i;
HT[min2_idx].parent = i;
}
}
void CreateHuffmanCode(HuffmanTree HT, HuffmanCode& HC, int n) {
HC = new char*[n];
char* code = new char[n];
code[n - 1] = '\0';
for (int i = 0; i < n; i++) {
int current = i;
int parent = HT[current].parent;
int idx = n - 1;
while (parent != -1) {
if (HT[parent].lchild == current) {
code[--idx] = '0';
} else {
code[--idx] = '1';
}
current = parent;
parent = HT[current].parent;
}
HC[i] = new char[n - idx];
strcpy(HC[i], &code[idx]);
}
delete[] code;
}
int main() {
int n;
cout << "Enter the number of characters: ";
cin >> n;
HuffmanTree HT;
CreateHuffmanTree(HT, n);
HuffmanCode HC;
CreateHuffmanCode(HT, HC, n);
cout << "Huffman codes:" << endl;
for (int i = 0; i < n; i++) {
cout << "Character '" << (char)('a' + i) << "': " << HC[i] << endl;
}
delete[] HT;
for (int i = 0; i < n; i++) {
delete[] HC[i];
}
delete[] HC;
return 0;
}
```
运行程序后,首先要输入字符的个数,然后输入每个字符的权重。程序会自动构建赫夫曼树并生成赫夫曼编码,最后输出每个字符的编码。注意,这里只支持输入小写字母,如果要支持其他字符,可以修改代码中的一些细节。
阅读全文