java 根据哈夫曼编码求哈夫曼树
时间: 2024-01-23 15:13:41 浏览: 70
用Java编写的哈夫曼树代码
4星 · 用户满意度95%
以下是Java中根据哈夫曼编码求哈夫曼树的示例代码:
```java
import java.util.PriorityQueue;
public class HuffmanTree {
public static Node buildTree(int[] charFreqs) {
PriorityQueue<Node> trees = new PriorityQueue<Node>();
for (int i = 0; i < charFreqs.length; i++) {
if (charFreqs[i] > 0) {
trees.offer(new LeafNode(charFreqs[i], (char) i));
}
}
assert trees.size() > 0;
while (trees.size() > 1) {
Node a = trees.poll();
Node b = trees.poll();
trees.offer(new InternalNode(a, b));
}
return trees.poll();
}
public static class Node implements Comparable<Node> {
public final int frequency;
public Node(int freq) {
frequency = freq;
}
public int compareTo(Node tree) {
return frequency - tree.frequency;
}
}
public static class InternalNode extends Node {
public final Node left, right;
public InternalNode(Node left, Node right) {
super(left.frequency + right.frequency);
this.left = left;
this.right = right;
}
}
public static class LeafNode extends Node {
public final char value;
public LeafNode(int freq, char val) {
super(freq);
value = val;
}
}
}
```
以上代码中,我们使用了优先队列来构建哈夫曼树。首先,我们将每个字符的出现频率作为权值,构建出叶子节点。然后,我们将所有叶子节点放入优先队列中,并不断取出队列中权值最小的两个节点,将它们合并成一个新的节点,并将新节点放回队列中。最终,队列中只剩下一个节点,即为哈夫曼树的根节点。
阅读全文