1. 程式人生 > >哈夫曼編碼(java)

哈夫曼編碼(java)

public class BinaryTree implements Comparable<BinaryTree>{
    int key;
    char data;
    //左子樹
    BinaryTree left;
    //右子樹
    BinaryTree right;
    public BinaryTree(){
     
    }
    public BinaryTree(int k,char d,BinaryTree l,BinaryTree r){
     key =k;
     data = d;
     left = l;
     right = r;
    }
   
    public String toString(){
     return "chracter: "+data+"frequence: "+ key;
    }
   
    public int compareTo(BinaryTree x){
     if(key>x.key){
      return 1;
     }
     else if(key<x.key){
      return -1;
     }
     else{
      return 0;
     }
    }
   
 public void inOrderWalk(){
  if(left!=null){
   left.inOrderWalk();
  }
  System.out.println(toString());
  if(right!=null){
   right.inOrderWalk();
  }
 }
 
     
}

 

import java.util.PriorityQueue;

public class Huffman {
     public static BinaryTree huffman(int[] f,char[] d){
      int i,n=f.length;
      //優先順序陣列
      PriorityQueue<BinaryTree> Q = new  PriorityQueue<BinaryTree>();
      //建立各個節點
      for(int m=0;m<n;m++){
       BinaryTree t = new BinaryTree(f[m],d[m],null,null);
       Q.add(t);
      }
      //生成哈夫曼樹
      for(int m=0;m<n-1;m++){
       BinaryTree x,y,z;
       x = Q.poll();//從優先順序佇列中彈出最小的元素x
       y = Q.poll();
       z= new BinaryTree(x.key+y.key,'*',x,y);
       Q.add(z);
      }
  return Q.poll();
     
     }
    
     public static void printCode(BinaryTree t,String c){
      if(t.left!=null){
       printCode(t.left,c+"0");
      }
      if(t.right!=null){
       printCode(t.right,c+"1");
      }
     
      if(t.left==null&&t.right==null){
       System.out.println(t+"code:"+ c+"");
      }
     }
    
     public static void main(String args[]){
      //出現的頻率
      int f[] = {45,13,12,16,9,5};
      //字元陣列
      char  d[] = {'a','b','c','d','e','f'};
      BinaryTree h = Huffman.huffman(f, d);
      //列印
      Huffman.printCode(h, "");
      //換行
      System.out.println();
     
     
     }
}