codeblocks实现键盘输入n值创建赫夫曼树代码
时间: 2023-06-08 18:05:06 浏览: 92
以下是使用 codeblocks 实现键盘输入 n 值创建赫夫曼树的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int weight; // 节点权值
struct node *left; // 左子树指针
struct node *right; // 右子树指针
} Node;
typedef struct heap {
int size; // 堆中节点数目
Node **data; // 存储节点指针的数组
} Heap;
// 创建一个新节点
Node *new_node(int weight) {
Node *node = (Node *) malloc(sizeof(Node));
node->weight = weight;
node->left = NULL;
node->right = NULL;
return node;
}
// 创建一个新的最小堆
Heap *new_heap(int max_size) {
Heap *heap = (Heap *) malloc(sizeof(Heap));
heap->size = 0;
heap->data = (Node **) malloc(sizeof(Node *) * max_size);
return heap;
}
// 合并两个最小堆,返回一个新的最小堆
Heap *merge(Heap *h1, Heap *h2) {
Heap *heap = new_heap(h1->size + h2->size);
int i = 0, j = 0, k = 0;
while (i < h1->size || j < h2->size) {
Node *node;
if (i >= h1->size) {
node = h2->data[j++];
} else if (j >= h2->size) {
node = h1->data[i++];
} else if (h1->data[i]->weight < h2->data[j]->weight) {
node = h1->data[i++];
} else {
node = h2->data[j++];
}
heap->data[k++] = node;
}
heap->size = k;
return heap;
}
// 创建赫夫曼树
Node *huffman_tree(int n) {
Heap *heap = new_heap(n);
for (int i = 0; i < n; i++) {
int weight;
printf("请输入第 %d 个节点的权值:", i + 1);
scanf("%d", &weight);
heap->data[i] = new_node(weight);
heap->size++;
}
while (heap->size > 1) {
Node *left = heap->data[0];
Node *right = heap->data[1];
Node *parent = new_node(left->weight + right->weight);
parent->left = left;
parent->right = right;
heap->data[1] = parent;
heap->size--;
for (int i = 1; i < heap->size; i++) {
heap->data[i] = heap->data[i + 1];
}
heap->data[0] = parent;
for (int i = 0; i < heap->size - 1; i++) {
if (heap->data[i]->weight > heap->data[i + 1]->weight) {
Node *temp = heap->data[i];
heap->data[i] = heap->data[i + 1];
heap->data[i + 1] = temp;
}
}
}
Node *root = heap->data[0];
free(heap->data);
free(heap);
return root;
}
int main() {
int n;
printf("请输入节点数目 n:");
scanf("%d", &n);
Node *root = huffman_tree(n);
printf("赫夫曼树的前序遍历结果为:");
pre_order(root);
printf("\n");
return 0;
}
```
注意,上述代码中的 `pre_order` 函数(用于前序遍历赫夫曼树)并未在代码中给出,你可以自己实现或者从网络上查找现成实现。
阅读全文