用Java语言写的构造哈夫曼树和哈夫曼编码的实例
时间: 2024-04-09 16:28:14 浏览: 98
当然,我可以帮你提供一个用Java语言编写的构造哈夫曼树和哈夫曼编码的实例。以下是一个简单的实现:
```java
import java.util.PriorityQueue;
class HuffmanNode implements Comparable<HuffmanNode> {
int frequency;
char data;
HuffmanNode left, right;
public HuffmanNode(char data, int frequency) {
this.data = data;
this.frequency = frequency;
left = right = null;
}
public int compareTo(HuffmanNode node) {
return frequency - node.frequency;
}
}
public class HuffmanCoding {
public static void main(String[] args) {
String text = "Hello, World!";
System.out.println("Original Text: " + text);
// 构造哈夫曼树
HuffmanNode root = buildHuffmanTree(text);
// 生成哈夫曼编码
String encodedText = encode(root, text);
System.out.println("Encoded Text: " + encodedText);
// 解码哈夫曼编码
String decodedText = decode(root, encodedText);
System.out.println("Decoded Text: " + decodedText);
}
public static HuffmanNode buildHuffmanTree(String text) {
int[] frequency = new int[256];
for (char c : text.toCharArray()) {
frequency[c]++;
}
PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<>();
for (char c = 0; c < 256; c++) {
if (frequency[c] > 0) {
priorityQueue.add(new HuffmanNode(c, frequency[c]));
}
}
while (priorityQueue.size() > 1) {
HuffmanNode left = priorityQueue.poll();
HuffmanNode right = priorityQueue.poll();
HuffmanNode newNode = new HuffmanNode('\0', left.frequency + right.frequency);
newNode.left = left;
newNode.right = right;
priorityQueue.add(newNode);
}
return priorityQueue.poll();
}
public static String encode(HuffmanNode root, String text) {
StringBuilder encodedText = new StringBuilder();
encodeHelper(root, text, encodedText);
return encodedText.toString();
}
private static void encodeHelper(HuffmanNode node, String text, StringBuilder encodedText) {
if (node == null) {
return;
}
if (node.left == null && node.right == null && Character.isLetter(node.data)) {
encodedText.append(node.data);
}
encodeHelper(node.left, text, encodedText);
encodeHelper(node.right, text, encodedText);
}
public static String decode(HuffmanNode root, String encodedText) {
StringBuilder decodedText = new StringBuilder();
HuffmanNode current = root;
for (char c : encodedText.toCharArray()) {
if (c == '0') {
current = current.left;
} else {
current = current.right;
}
if (current.left == null && current.right == null) {
decodedText.append(current.data);
current = root;
}
}
return decodedText.toString();
}
}
```
这个实例演示了如何构建哈夫曼树,并使用树来对给定的文本进行编码和解码。在这个例子中,我们首先统计给定文本中每个字符出现的频率,然后根据频率构造哈夫曼树。最后,使用哈夫曼树对原始文本进行编码,并将编码后的文本进行解码以还原原始文本。
希望这个实例可以帮助到你!如果你还有其他问题,请随时向我提问。
阅读全文