Java 哈夫曼编码-如何引用哈夫曼树顶部的节点?

Java 哈夫曼编码-如何引用哈夫曼树顶部的节点?,java,tree,huffman-code,Java,Tree,Huffman Code,这个程序应该获取一个文件并用哈夫曼代码压缩它。我的问题是,在我的Coder方法中,我必须使用元素X来引用哈夫曼树的顶部: public static String Coder(Element Z){ Element X = Z; if(Z != null){ Coder(Z.left); if(Z.isleaf()){ Element K = Z;

这个程序应该获取一个文件并用哈夫曼代码压缩它。我的问题是,在我的
Coder
方法中,我必须使用
元素X
来引用哈夫曼树的顶部:

     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;
   }
}
这样X在递归运行
Coder
时不会被覆盖。 此程序中的节点称为
元素
。pq是另一个具有堆结构的优先级程序的一部分

这是孔编码类

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;
   }
}

这还不清楚。这里的问题是什么?“这样在递归运行
Coder
时X不会被覆盖”。。您只需在
Coder
本地范围之外定义
X
(例如,作为实例属性)。问题是什么?还要记住a)将对象与
==
进行比较是不明智的=和b)Java命名约定要求变量名以小写字母开头。
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;
    }
  }
}