哈夫曼树
1. 哈夫曼树的定义
2. 哈夫曼树的构造
class HuffmanNode {
int data;
int weight;
HuffmanNode left;
HuffmanNode right;
public HuffmanNode(int weight) {
this.weight = weight;
}
}
public class HuffmanTree {
public HuffmanNode huffman(HuffmanNode[] nodes) {
PriorityQueue<HuffmanNode> minHeap = new PriorityQueue<>(Comparator.comparingInt(o -> o.weight));
minHeap.addAll(Arrays.asList(nodes));
while (minHeap.size() > 1) {
HuffmanNode root = new HuffmanNode(0);
root.left = minHeap.poll();
root.right = minHeap.poll();
assert root.right != null;
root.weight = root.left.weight + root.right.weight;
minHeap.add(root);
}
return minHeap.poll();
}
// A utility function to print preorder traversal
// of the tree.
// The function also prints height of every node
public void preOrder(HuffmanNode node) {
if (node != null) {
System.out.print(node.weight + " ");
preOrder(node.left);
preOrder(node.right);
}
}
@Test
public void test() {
HuffmanNode[] huffmanNodes = new HuffmanNode[5];
for (int i = 0; i < 5; i++) {
huffmanNodes[i] = new HuffmanNode( i + 1);
}
HuffmanNode root = huffman(huffmanNodes);
preOrder(root);
}
}3. 哈夫曼树的特点
4. 哈夫曼编码

最后更新于