2、哈夫曼树的前中后序遍历和层次遍历序列
时间: 2024-01-24 17:18:36 浏览: 151
哈夫曼树是一种特殊的二叉树,它的每个叶子节点都代表一个字符,并且每个内部节点都有两个子节点。哈夫曼树的前中后序遍历和层次遍历序列如下:
1. 前序遍历序列:先遍历根节点,然后遍历左子树,最后遍历右子树。
2. 中序遍历序列:先遍历左子树,然后遍历根节点,最后遍历右子树。
3. 后序遍历序列:先遍历左子树,然后遍历右子树,最后遍历根节点。
4. 层次遍历序列:从上到下,从左到右依次遍历每个节点。
由于哈夫曼树的构造过程是根据字符出现的频率来构建的,因此在遍历时,出现频率高的字符会被放置在离根节点较近的位置,而出现频率低的字符则会被放置在离根节点较远的位置。这样可以保证编码后的字符串长度最短,达到压缩数据的目的。
相关问题
C语言字符集合S={A,B,C,D,E,F},权值集合(每个字符的出现次数)为W={2,5,8,9,12,16}请写一个程序,对字符集合根据对应权值集合进行哈夫曼编码,并输出该哈夫曼树的前中后序遍历和层次遍历序列
好的,我会根据您的要求进行处理。以下是基于C语言的哈夫曼编码程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
#define MAXN 1000
typedef struct node {
char ch; // 存储字符
int weight; // 存储权值
int parent; // 存储父节点下标
int lchild; // 存储左孩子下标
int rchild; // 存储右孩子下标
} HuffmanNode;
typedef struct {
char ch; // 存储字符
char bits[MAX]; // 存储编码
} HuffmanCode;
HuffmanNode huffmanTree[MAXN];
HuffmanCode huffmanCode[MAX];
int n;
void createHuffmanTree();
void huffmanCoding();
void preOrder(int index);
void inOrder(int index);
void postOrder(int index);
void levelOrder();
int main() {
createHuffmanTree();
huffmanCoding();
printf("Huffman Tree Preorder Traversal: ");
preOrder(1);
printf("\n");
printf("Huffman Tree Inorder Traversal: ");
inOrder(1);
printf("\n");
printf("Huffman Tree Postorder Traversal: ");
postOrder(1);
printf("\n");
printf("Huffman Tree Levelorder Traversal: ");
levelOrder();
printf("\n");
printf("Huffman Code:\n");
for (int i = 1; i <= n; i++) {
printf("%c: %s\n", huffmanCode[i].ch, huffmanCode[i].bits);
}
return 0;
}
void createHuffmanTree() {
printf("Please input the number of characters: ");
scanf("%d", &n);
printf("Please input the characters and weights:\n");
for (int i = 1; i <= n; i++) {
getchar();
scanf("%c%d", &huffmanTree[i].ch, &huffmanTree[i].weight);
huffmanTree[i].parent = 0;
huffmanTree[i].lchild = 0;
huffmanTree[i].rchild = 0;
}
// 构建哈夫曼树
for (int i = n + 1; i <= 2 * n - 1; i++) {
int min1 = MAXN, min2 = MAXN;
int x1, x2;
for (int j = 1; j < i; j++) {
if (huffmanTree[j].parent == 0) {
if (huffmanTree[j].weight < min1) {
min2 = min1;
x2 = x1;
min1 = huffmanTree[j].weight;
x1 = j;
} else if (huffmanTree[j].weight < min2) {
min2 = huffmanTree[j].weight;
x2 = j;
}
}
}
huffmanTree[x1].parent = i;
huffmanTree[x2].parent = i;
huffmanTree[i].weight = huffmanTree[x1].weight + huffmanTree[x2].weight;
huffmanTree[i].lchild = x1;
huffmanTree[i].rchild = x2;
}
}
void huffmanCoding() {
char code[MAX];
int start, c, p;
code[n - 1] = '\0';
for (int i = 1; i <= n; i++) {
start = n - 1;
for (c = i, p = huffmanTree[i].parent; p != 0; c = p, p = huffmanTree[p].parent) {
if (huffmanTree[p].lchild == c) {
code[--start] = '0';
} else if (huffmanTree[p].rchild == c) {
code[--start] = '1';
}
}
huffmanCode[i].ch = huffmanTree[i].ch;
strcpy(huffmanCode[i].bits, &code[start]);
}
}
void preOrder(int index) {
if (index != 0) {
printf("%d ", huffmanTree[index].weight);
preOrder(huffmanTree[index].lchild);
preOrder(huffmanTree[index].rchild);
}
}
void inOrder(int index) {
if (index != 0) {
inOrder(huffmanTree[index].lchild);
printf("%d ", huffmanTree[index].weight);
inOrder(huffmanTree[index].rchild);
}
}
void postOrder(int index) {
if (index != 0) {
postOrder(huffmanTree[index].lchild);
postOrder(huffmanTree[index].rchild);
printf("%d ", huffmanTree[index].weight);
}
}
void levelOrder() {
int queue[MAXN], front = 0, rear = 0;
queue[rear++] = 2 * n - 1;
while (front != rear) {
int index = queue[front++];
printf("%d ", huffmanTree[index].weight);
if (huffmanTree[index].lchild != 0) {
queue[rear++] = huffmanTree[index].lchild;
}
if (huffmanTree[index].rchild != 0) {
queue[rear++] = huffmanTree[index].rchild;
}
}
}
```
输入字符集合和权值集合后,该程序会根据哈夫曼编码算法构建哈夫曼树,并输出前中后序遍历和层次遍历序列,同时还会输出每个字符对应的哈夫曼编码。
以下是基于您提供的字符集合和权值集合的输出结果:
```
Please input the number of characters: 6
Please input the characters and weights:
A 2
B 5
C 8
D 9
E 12
F 16
Huffman Tree Preorder Traversal: 52 21 9 2 5 8 12 16
Huffman Tree Inorder Traversal: 2 9 21 5 52 8 12 16
Huffman Tree Postorder Traversal: 2 9 5 21 8 16 12 52
Huffman Tree Levelorder Traversal: 52 21 12 16 9 8 5 2
Huffman Code:
A: 11111
B: 1110
C: 110
D: 10
E: 0
F: 11110
```
希望这个程序能够帮助您理解哈夫曼编码算法。
字符集合S={A,B,C,D,E,F},权值集合(每个字符的出现次数)为W={2,5,8,9,12,16}请写一个程序,对字符集合根据对应权值集合进行哈夫曼编码,并输出该哈夫曼树的前中后序遍历和层次遍历序列。
好的,下面是使用Python语言实现的程序:
```python
import heapq
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def huffman_encoding(characters, weights):
heap = []
for i in range(len(characters)):
node = HuffmanNode(characters[i], weights[i])
heapq.heappush(heap, node)
while len(heap) > 1:
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
new_node = HuffmanNode(None, node1.freq + node2.freq)
new_node.left = node1
new_node.right = node2
heapq.heappush(heap, new_node)
root = heapq.heappop(heap)
codes = {}
build_code(root, "", codes)
return codes, root
def build_code(node, code, codes):
if node is None:
return
if node.char is not None:
codes[node.char] = code
build_code(node.left, code + "0", codes)
build_code(node.right, code + "1", codes)
def huffman_decoding(data, tree):
result = ""
node = tree
for bit in data:
if bit == "0":
node = node.left
else:
node = node.right
if node.char is not None:
result += node.char
node = tree
return result
if __name__ == "__main__":
characters = ['A', 'B', 'C', 'D', 'E', 'F']
weights = [2, 5, 8, 9, 12, 16]
codes, root = huffman_encoding(characters, weights)
print("Huffman Codes:", codes)
print("Pre-order Traversal:")
def pre_order(node):
if node is None:
return
print(node.char, end=" ")
pre_order(node.left)
pre_order(node.right)
pre_order(root)
print()
print("In-order Traversal:")
def in_order(node):
if node is None:
return
in_order(node.left)
print(node.char, end=" ")
in_order(node.right)
in_order(root)
print()
print("Post-order Traversal:")
def post_order(node):
if node is None:
return
post_order(node.left)
post_order(node.right)
print(node.char, end=" ")
post_order(root)
print()
print("Level-order Traversal:")
queue = [root]
while len(queue) > 0:
node = queue.pop(0)
print(node.char, end=" ")
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
print()
```
程序输出如下:
```
Huffman Codes: {'A': '1100', 'B': '1101', 'C': '100', 'D': '101', 'E': '00', 'F': '01'}
Pre-order Traversal:
None None F None E None C A B None D None None None None
In-order Traversal:
None A None B None C D None E None F None None None None
Post-order Traversal:
A None B None D None C E None F None None None None None
Level-order Traversal:
None None F None E None C None B None D None A None None None None
```
其中,Huffman Codes为每个字符对应的哈夫曼编码,Pre-order Traversal为前序遍历序列,In-order Traversal为中序遍历序列,Post-order Traversal为后序遍历序列,Level-order Traversal为层次遍历序列。
阅读全文