用Java编写显示哈夫曼树的树形结构的代码
时间: 2024-04-13 21:30:33 浏览: 92
用Java编写的哈夫曼树代码
4星 · 用户满意度95%
以下是一个用Java编写的显示哈夫曼树树形结构的简单示例代码:
```java
import java.util.PriorityQueue;
class HuffmanNode implements Comparable<HuffmanNode> {
char c;
int frequency;
HuffmanNode left, right;
public HuffmanNode(char c, int frequency) {
this.c = c;
this.frequency = frequency;
}
public int compareTo(HuffmanNode node) {
return this.frequency - node.frequency;
}
}
public class HuffmanTreeDisplay {
public static void main(String[] args) {
String text = "Hello, world!";
HuffmanNode root = buildHuffmanTree(text);
displayHuffmanTree(root, "");
}
public static HuffmanNode buildHuffmanTree(String text) {
int[] frequency = new int[256];
for (char c : text.toCharArray()) {
frequency[c]++;
}
PriorityQueue<HuffmanNode> pq = new PriorityQueue<>();
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] > 0) {
pq.offer(new HuffmanNode((char) i, frequency[i]));
}
}
while (pq.size() > 1) {
HuffmanNode left = pq.poll();
HuffmanNode right = pq.poll();
HuffmanNode parent = new HuffmanNode('\0', left.frequency + right.frequency);
parent.left = left;
parent.right = right;
pq.offer(parent);
}
return pq.poll();
}
public static void displayHuffmanTree(HuffmanNode root, String prefix) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
System.out.println(root.c + " -> " + prefix);
}
displayHuffmanTree(root.left, prefix + "0");
displayHuffmanTree(root.right, prefix + "1");
}
}
```
这段代码实现了以下几个功能:
- `buildHuffmanTree` 函数根据输入的文本构建哈夫曼树。
- `displayHuffmanTree` 函数用于递归地显示哈夫曼树的树形结构,并打印每个字符对应的编码。
在 `main` 函数中,我们使用字符串 "Hello, world!" 来构建哈夫曼树,并显示其树形结构和字符编码。你可以根据自己的需求修改 `main` 函数中的文本内容。
阅读全文