Huffman tree wrong output
this is my first time using stackoverflow to ask a question and i hope you
guys can help me out :)
i am working on a projecting to implement Huffman code. The problem is
that i got a wrong result when i try to print the code.
Here is the input file and correct result:
Symbol A B C D _
frequency 0.35 0.1 0.2 0.2 0.15
Code 11 100 00 01 101
the result i got:
Symbol A B C D _
frequency 0.35 0.1 0.2 0.2 0.15
Code 0 110 0 11 0
Here is the class file:
import java.util.*;
import java.io.*;
import java.util.PriorityQueue;
public class Node implements Comparable<Node> {
Node left;
Node right;
Node parent;
String text;
Float frequency;
public Node(String textIn, Float frequencies) {
text = textIn;
frequency = frequencies;
}
public Node(Float d) {
text = "";
frequency = d;
}
public int compareTo(Node n) {
if (frequency < n.frequency) {
return -1;
} else if (frequency > n.frequency) {
return 1;
}
return 0;
}
public static void printFromPreOrder(Node n) {
if (n.left != null) {
printFromPreOrder(n.left);
System.out.println("0");
}
if (n.text != null) {
System.out.print(n.text);
}
if (n.right != null) {
printFromPreOrder(n.right);
System.out.print("1");
}
}
// Returns root node to pass to printFromPreOrder
public static Node makeHuffmanTree(Float[] frequencies, String text[]) {
PriorityQueue<Node> queue = new PriorityQueue<Node>();
for (int i = 0; i < text.length; i++) {
Node n = new Node(text[i], frequencies[i]);
queue.add(n);
}
Node root = null;
while (queue.size() > 1) {
Node least1 = queue.poll();
Node least2 = queue.poll();
Node combined = new Node(least1.frequency + least2.frequency);
combined.right = least1;
combined.left = least2;
least1.parent = combined;
least2.parent = combined;
queue.add(combined);
// Keep track until we actually find the root
root = combined;
}
return root;
}
I think there is something wrong with my printing method?
No comments:
Post a Comment