哈夫曼树以其编码解码
要求:
1.从终端读入字符集大小为n(即字符的个数),逐一输入n个字符和相应的n个权值(即字符出现的频度),建立哈夫曼树,进行编码并且输出。
将它存于文件hfmtree中(选做)。
2.利用已建好的哈夫曼编码文件hfmtree,对键盘输入的正文进行译码。输出字符正文,再输出该文的二进制码。
[测试数据]
用下表中给出的字符集(n=27)和频度的实际统计数据建立哈夫曼树:
并实现以下报文的译码和输出:“THIS PROGRAM IS MY FAVORITE”。
结点代码:
public class HNode {
public String code = "";// 节点的哈夫曼编码
public String data = "";// 节点的数据
public int count;// 节点的权值
public HNode lChild;
public HNode rChild;
public HNode() {
}
public HNode(String data, int count) {
this.data = data;
this.count = count;
}
public HNode(int count, HNode lChild, HNode rChild) {
this.count = count;
this.lChild = lChild;
this.rChild = rChild;
}
public HNode(String data, int count, HNode lChild, HNode rChild) {
this.data = data;
this.count = count;
this.lChild = lChild;
this.rChild = rChild;
}
}
哈夫曼树及编码解码
public class Huffman {
private String str;// 字符串
private HNode root;// 哈夫曼二叉树的根节点
private boolean flag;// 最新的字符是否已经存在的标签
private LinkedList<CharData> charList;// 存储不同字符的队列 相同字符存在同一位置
private LinkedList<HNode> NodeList;// 存储节点的队列
private class CharData {
int num = 1; // 字符个数
char c; // 字符
public CharData(char ch){
c = ch;
}
}
/**
* 构建哈夫曼树
*/
public void creatHfmTree(String str) {
this.str = str;
NodeList = new LinkedList<HNode>();
charList = new LinkedList<CharData>();
// 1.统计字符串中字符以及字符的出现次数
// 以