该程序应该获取一个文件并使用霍夫曼代码对其进行压缩。我的问题是我必须Element X
使用Coder
方法引用霍夫曼树的顶部:
public static String Coder(Element Z){
Element X = Z;
if(Z != null){
Coder(Z.left);
if(Z.isleaf()){
Element K = Z;
Code = "";
while(K != X){ //here I want X to be reference the top of my huffman tree
if(K == K.parent.left){
Code = Code+0;
}else{
Code = Code+1;
}
K = K.parent;
}
}Coder(Z.right);
}
return Code;
}
}
因此在递归运行Coder
时X不会被覆盖。
此程序中的节点称为Element
。 pq是另一个程序的一部分,它是一个具有堆结构的prioritycue。
这是洞编码类
import java.io.FileInputStream;
public class Encode{
static int[] Freq=new int[256];
static PQ pq = new PQHeap(256);
static String Code;
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("C:\\Java\\testfilen.txt");
Inputstream.Inputs(fis);
for(int i=0; i<Freq.length; i++){
pq.insert(new Element(Freq[i],new Integer(i)));
}
Element Z = Huffman();
String K = Coder(Z);
System.out.println(K);
}
public static Element Huffman(){
int n = Freq.length;
for(int i=1; i<=n-1; i++){
Element z = new Element(0, 0);
Element x=pq.extractMin();
z.left=x;
Element y=pq.extractMin();
z.right=y;
z.key = y.key+x.key;
pq.insert(z);
}
return pq.extractMin();
}
public static String Coder(Element Z){
Element X = Z;
if(Z != null){
Coder(Z.left);
if(Z.isleaf()){
Element K = Z;
Code = "";
while(K != X){
if(K == K.parent.left){
Code = Code+0;
}else{
Code = Code+1;
}
K = K.parent;
}
}Coder(Z.right);
}
return Code;
}
}
这是Element
类
public class Element {
public int key;
public Object data;
public Element parent;
public Element left;
public Element right;
public Element(int i, Object o){
this.key = i;
this.data = o;
this.parent = null;
this.left=null;
this.right=null;
}
public boolean isleaf(){
if(this.left == null && this.right == null){
return true;
}else{
return false;
}
}
}