이있는 질문을하고 난 너희들이이 허프만 코드를 구현하는 투사에 :) 내가하고 있어요허프만 트리 잘못 출력
나를 도울 수 희망 유래를 사용하여 내 첫 번째 시간입니다. 문제는 코드를 인쇄하려고 할 때 잘못된 결과가 발생한다는 것입니다.
Symbol A B C D _
frequency 0.35 0.1 0.2 0.2 0.15
Code 11 100 00 01 101
내가 가진 결과 : 뭔가가 있다고 생각
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 buildPath(Node root,String code)
{
if (root!=null)
{
if (root.left!=null)
buildPath(root.left, code+"0");
if (root.right!=null)
buildPath(root.right,code+"1");
if (root.left==null && root.right==null)
System.out.println(root.text+": "+code);
}
}
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;
}
:
여기Symbol A B C D _
frequency 0.35 0.1 0.2 0.2 0.15
Code 00 011 10 11 010
클래스 파일입니다 여기에
입력 파일 및 올바른 결과입니다 내 인쇄 방법에 문제가 있니?과 출력에서
public static void main(String[] args)
String[] Symbol = {"A","B","C","D","_"};
Float[] frequency = (0.35,0.1,0.2,0.2,0.15};
Node root = Node.makeHuffmanTree(frequency, Symbol);
Node.buildPath(root, "");
인쇄 방법에 대해 인쇄 방법이 정확히 무엇을 기대합니까? 접두사 순서대로, 순서대로 또는 무엇으로 인쇄합니까? –
'printFromPreOrder' 메서드가 무엇을하는지 이해할 수 없습니다. 코드를 인쇄하려고 할 때 루트에서 각 리프 노드까지의 경로를 찾으려고하지 않아야합니까? 나는 이것이 당신이 노드에 저장 한 텍스트와 관련이 있다고 생각하지 않는다. – Zhe
mmm 각 노드의 경로는 어떻게 찾습니까? 나는 내가 왼쪽 지점을 가져 가면 1을 인쇄 할 때 0을 인쇄해야한다는 것을 알고있다. – Samson