哈夫曼树生成代码Java
时间: 2023-10-28 14:06:14 浏览: 94
以下是Java中生成哈夫曼树的代码:
```java
import java.util.PriorityQueue;
class HuffmanNode implements Comparable<HuffmanNode> {
int frequency;
char data;
HuffmanNode left, right;
public int compareTo(HuffmanNode node) {
return frequency - node.frequency;
}
}
public class HuffmanTree {
public static void main(String[] args) {
String message = "hello world";
HuffmanNode root = buildTree(message);
String encodedMessage = encode(root, message);
System.out.println("Encoded message: " + encodedMessage);
String decodedMessage = decode(root, encodedMessage);
System.out.println("Decoded message: " + decodedMessage);
}
public static HuffmanNode buildTree(String message) {
int[] frequency = new int[256];
for (int i = 0; i < message.length(); i++) {
frequency[message.charAt(i)]++;
}
PriorityQueue<HuffmanNode> pq = new PriorityQueue<>();
for (char i = 0; i < 256; i++) {
if (frequency[i] > 0) {
HuffmanNode node = new HuffmanNode();
node.data = i;
node.frequency = frequency[i];
node.left = null;
node.right = null;
pq.add(node);
}
}
while (pq.size() > 1) {
HuffmanNode left = pq.poll();
HuffmanNode right = pq.poll();
HuffmanNode parent = new HuffmanNode();
parent.frequency = left.frequency + right.frequency;
parent.data = '-';
parent.left = left;
parent.right = right;
pq.add(parent);
}
return pq.poll();
}
public static String encode(HuffmanNode root, String message) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
char c = message.charAt(i);
HuffmanNode node = findNode(root, c);
builder.append(node.data);
}
return builder.toString();
}
public static String decode(HuffmanNode root, String encodedMessage) {
StringBuilder builder = new StringBuilder();
HuffmanNode node = root;
for (int i = 0; i < encodedMessage.length(); i++) {
char c = encodedMessage.charAt(i);
if (c == '0') {
node = node.left;
} else {
node = node.right;
}
if (node.left == null && node.right == null) {
builder.append(node.data);
node = root;
}
}
return builder.toString();
}
public static HuffmanNode findNode(HuffmanNode root, char c) {
if (root == null) {
return null;
}
if (root.data == c) {
return root;
}
HuffmanNode left = findNode(root.left, c);
if (left != null) {
return left;
}
HuffmanNode right = findNode(root.right, c);
if (right != null) {
return right;
}
return null;
}
}
```
这个代码中,`HuffmanNode`类表示哈夫曼树的节点,包含数据、频率以及左右子节点。`buildTree`方法根据输入的消息构建哈夫曼树,`encode`方法将输入的消息编码成哈夫曼编码,`decode`方法将哈夫曼编码解码成原始消息。`findNode`方法用来查找某个字符在哈夫曼树中对应的节点。
阅读全文