已知下列字符 A、B、C、D、E、F、G 的权值分别为 3、12、7、4、2、8, 11,试填写出其对应哈夫曼树 HT 的存储结构的初态和终态
时间: 2023-09-29 08:08:36 浏览: 100
初态:
```
typedef struct {
int weight; // 权值
int parent; // 父结点下标
int leftChild; // 左孩子下标
int rightChild; // 右孩子下标
} HTNode, *HuffmanTree;
HuffmanTree HT = NULL;
int n = 7; // 结点数
// 初始化每个结点
HT = (HuffmanTree) malloc((2 * n - 1) * sizeof(HTNode));
for (int i = 0; i < n; i++) {
HT[i].weight = weights[i];
HT[i].parent = -1;
HT[i].leftChild = -1;
HT[i].rightChild = -1;
}
```
终态:
```
// 建立哈夫曼树
for (int i = n; i < 2 * n - 1; i++) {
int min1 = INT_MAX, min2 = INT_MAX; // 最小的两个权值
int x1 = -1, x2 = -1; // 最小的两个权值对应的结点下标
for (int j = 0; j < i; j++) {
if (HT[j].parent == -1) {
if (HT[j].weight < min1) {
min2 = min1;
x2 = x1;
min1 = HT[j].weight;
x1 = j;
} else if (HT[j].weight < min2) {
min2 = HT[j].weight;
x2 = j;
}
}
}
HT[x1].parent = i;
HT[x2].parent = i;
HT[i].weight = HT[x1].weight + HT[x2].weight;
HT[i].leftChild = x1;
HT[i].rightChild = x2;
}
```
阅读全文