import java.util.Comparator;
import java.util.PriorityQueue;
public class HuffMan {
public static void main(String[] args) {
PriorityQueue<Node1> q = new PriorityQueue<Node1>(new Comparator<Node1>() {
public int compare(Node1 n1, Node1 n2) {
return n1.freq.compareTo(n2.freq);
}
});
q.add(new Node1('a',2));
q.add(new Node1('b',2));
q.add(new Node1('c',3));
q.add(new Node1('d',3));
q.add(new Node1('e',5));
q.add(new Node1('f',6));
q.add(new Node1('g',7));
while(q.size()>1) {
Node1 n1 = q.poll();
Node1 n2 = q.poll();
Node1 n3 = new Node1(' ',n1.freq+n2.freq);
n3.l = n1;
n3.r = n2;
q.add(n3);
}
dfs(q.peek(),"");
print(q.peek());
}
private static void print(Node1 root) {
if(root.l == null && root.r == null) System.out.println(root.val+" "+root.freq+" "+root.code);
else {
if(root.l != null) print(root.l);
if(root.r != null) print(root.r);
}
}
private static void dfs(Node1 root,String prefix) {
if(root.l == null && root.r == null) root.code = prefix;
else {
if(root.l != null) dfs(root.l,prefix+"0");
if(root.r != null) dfs(root.r,prefix+"1");
}
}
}
class Node1 {
Node1 l;
Node1 r;
char val;
Integer freq;
String code;
public Node1(char val,int freq) {
l = r = null;
this.val = val;
this.freq = freq;
}
}
No comments:
Post a Comment