用Java语言实现一下哈夫曼树代码
时间: 2023-09-16 13:06:36 浏览: 90
以下是Java语言实现的哈夫曼树代码:
```java
import java.util.PriorityQueue;
public class HuffmanTree {
// 定义哈夫曼树节点
private static class HuffmanNode implements Comparable<HuffmanNode> {
int value; // 节点的权值
HuffmanNode left; // 左子节点
HuffmanNode right; // 右子节点
public HuffmanNode(int value) {
this.value = value;
}
@Override
public int compareTo(HuffmanNode o) {
return this.value - o.value;
}
}
// 构建哈夫曼树
public static HuffmanNode buildHuffmanTree(int[] weights) {
PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<>();
for (int weight : weights) {
priorityQueue.offer(new HuffmanNode(weight));
}
while (priorityQueue.size() > 1) {
HuffmanNode leftNode = priorityQueue.poll();
HuffmanNode rightNode = priorityQueue.poll();
HuffmanNode parentNode = new HuffmanNode(leftNode.value + rightNode.value);
parentNode.left = leftNode;
parentNode.right = rightNode;
priorityQueue.offer(parentNode);
}
return priorityQueue.poll();
}
// 前序遍历哈夫曼树
public static void preOrderTraversal(HuffmanNode root) {
if (root != null) {
System.out.print(root.value + " ");
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
}
public static void main(String[] args) {
int[] weights = {5, 2, 13, 8};
HuffmanNode root = buildHuffmanTree(weights);
preOrderTraversal(root); // 28 13 5 2
}
}
```
注:以上代码中,我们使用了Java中的优先队列(PriorityQueue)来实现哈夫曼树的构建。哈夫曼树的构建过程是一个贪心算法,优先队列的内部实现是堆,能够很好地支持贪心算法。
阅读全文