私はこのハフマンツリービルダーに取り組んできました:
// variable al is an array list that holds all the different characters and their frequencies
// variable r is a Frequency which is supposed to be the roots for all the leaves which holds a null string and the frequencies of the combined nodes removed from the priority queue
public Frequency buildTree(ArrayList<Frequency> al)
{
Frequency r = al.get(0);
PriorityQueue<Frequency> pq = new PriorityQueue<Frequency>();
for(int i = 0; i < al.size(); i++)
{
pq.add(al.get(i));
}
/*while(pq.size() > 0)
{
System.out.println(pq.remove().getString());
}*/
for(int i = 0; i < al.size() - 1; i++)
{
Frequency p = pq.remove();
Frequency q = pq.remove();
int temp = p.getFreq() + q.getFreq();
r = new Frequency(null, temp);
r.left = p;
r.right = q;
pq.add(r); // put in the correct place in the priority queue
}
pq.remove(); // leave the priority queue empty
return(r); // this is the root of the tree built
}
コードが英語でやろうとしていることは
すべての文字を頻度とともに優先キューに最低頻度から最高頻度まで追加します。次に、ArrayList al (すべての文字を含む) のサイズについて、最初の 2 つをデキューし、デキューされた 2 つのノードである左と右の子を持つように新しいルートを設定し、デキューされた 2 つの結合された頻度で新しいルートを挿入します。アイテムを優先キューに入れます。メソッドが行うべきことはそれだけです。
このメソッドはハフマン ツリーを構築することになっていますが、正しく構築されていません コードに従ってツリーを手動で構築しましたが、紙に書かれていることはプログラムとは異なります。別のプログラムによって生成された正解は、私の解と同じではありません。入力データ (文字と頻度) は次のとおりです。
a 6
b 5
space 5
c 4
d 3
e 2
f 1
周波数はすでにここにあるので、それから読んでいるテキストは問題ではありません。必要なのは、これらの周波数からツリーを構築することだけです。