package org.orithmetic.greedySelector;
public class Node<T> implements Comparable<Node<T>>{
private T data;
private int weigth;
private Node<T> left;
private Node<T> 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<T> getLeft() {
return left;
}
public void setLeft(Node<T> left) {
this.left = left;
}
public Node<T> getRight() {
return right;
}
public void setRight(Node<T> right) {
this.right = right;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
public int compareTo(Node<T> node) {
// TODO Auto-generated method stub
if(node.getWeigth()>this.getWeigth())
return 1;
if(node.getWeigth()<this.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<T> {
private void createTree(List<Node<T>> list){
while(list.size()>1){
Collections.sort(list);
Node<T> left = list.get(list.size()-1);
Node<T> right = list.get(list.size()-2);
Node<T> parent = new Node<T>(null,left.getWeigth()+right.getWeigth());
parent.setLeft(left);
parent.setRight(right);
list.remove(left);
list.remove(right);
list.add(parent);
}
}
public static <T> void huffman(Node<T> 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<Node<String>> list = new ArrayList<Node<String>>();
list.add(new Node<String>(“f”,5));
list.add(new Node<String>(“e”,9));
list.add(new Node<String>(“d”,16));
list.add(new Node<String>(“c”,12));
list.add(new Node<String>(“b”,13));
list.add(new Node<String>(“a”,45));
HuffmanTree<String> tree =new HuffmanTree<String>();
tree.createTree(list);
Node<String> 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));
}
}
}