package org.orithmetic.greedySelector;
public class Node implements Comparable>{
private T data;
private int weigth;
private Node left;
private Node right;
public Node(T data,int weigth){
this.data=data;
this.weigth=weigth;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public int getWeigth() {
return weigth;
}
public void setWeigth(int weigth) {
this.weigth = weigth;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
public int compareTo(Node node) {
// TODO Auto-generated method stub
if(node.getWeigth()>this.getWeigth())
return 1;
if(node.getWeigth()
return -1;
return 0;
}
}
package org.orithmetic.greedySelector; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class HuffmanTree { private void createTree(List> list){ while(list.size()>1){ Collections.sort(list); Node left = list.get(list.size()-1); Node right = list.get(list.size()-2); Node parent = new Node(null,left.getWeigth()+right.getWeigth()); parent.setLeft(left); parent.setRight(right); list.remove(left); list.remove(right); list.add(parent); } } public static void huffman(Node root,String code,Map map){ if(root == null) return; if(root.getLeft()==null && root.getRight()==null){ map.put(root.getData(), code); return; } code+="1"; huffman(root.getRight(),code,map); code=code.substring(0, code.length()-1); code+="0"; huffman(root.getLeft(),code,map); } public static void main(String[] args) { // TODO Auto-generated method stub List> list = new ArrayList>(); list.add(new Node("f",5)); list.add(new Node("e",9)); list.add(new Node("d",16)); list.add(new Node("c",12)); list.add(new Node("b",13)); list.add(new Node("a",45)); HuffmanTree tree =new HuffmanTree(); tree.createTree(list); Node root = list.get(0); String code=""; Map map=new HashMap(); huffman(root,code,map); Iterator ite = map.keySet().iterator(); while(ite.hasNext()){ String key = (String) ite.next(); System.out.println(key+"的编码:"+map.get(key)); } } }