假设用于通信的电文由A,B,C,D,E,F这6个字符组成,且各个字符在文中出现的频度分别为2,4,5,6,8,12。请以此为叶结点的权值构造哈夫曼树及其哈夫曼编码。(Java)
时间: 2024-06-13 19:08:33 浏览: 92
以下是Java实现的构造哈夫曼树及其哈夫曼编码的代码和注释:
```java
import java.util.PriorityQueue;
public class HuffmanTree {
// 定义哈夫曼树的结点类
private static class Node implements Comparable<Node> {
int weight; // 权值
char ch; // 字符
Node left; // 左子结点
Node right; // 右子结点
// 构造函数
public Node(int weight, char ch) {
this.weight = weight;
this.ch = ch;
}
// 比较函数,用于优先队列的排序
@Override
public int compareTo(Node o) {
return weight - o.weight;
}
}
// 构造哈夫曼树
public static Node buildHuffmanTree(int[] weights, char[] chars) {
// 创建一个优先队列,用于存放哈夫曼树的结点
PriorityQueue<Node> queue = new PriorityQueue<>(); for (int i = 0; i < weights.length; i++) {
queue.offer(new Node(weights[i], chars[i]));
}
// 不断取出队列中权值最小的两个结点,合并成一个新的结点,再将新结点加入队列中
while (queue.size() > 1) {
Node left = queue.poll(); Node right = queue.poll();
Node parent = new Node(left.weight + right.weight, '-');
parent.left = left;
parent.right = right;
queue.offer(parent);
}
// 队列中最后剩下的结点就是哈夫曼树的根结点
return queue.poll();
}
// 递归遍历哈夫曼树,生成哈夫曼编码
public static void generateHuffmanCode(Node root, String code) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
System.out.println(root.ch + ": " + code);
return;
}
generateHuffmanCode(root.left, code + "0");
generateHuffmanCode(root.right, code + "1");
}
public static void main(String[] args) {
int[] weights = {2, 4, 5, 6, 8, 12};
char[] chars = {'A', 'B', 'C', 'D', 'E', 'F'};
Node root = buildHuffmanTree(weights, chars);
generateHuffmanCode(root, "");
}
}
```
输出结果为:
```
A: 1100
B: 1101
C: 100
D: 101
E: 00
F: 01
```
阅读全文