宿題で最大周波数を見つける:両方どのように多くのユニークワードファイル 内を知ることができるようにするためにバランスの取れたツリー[宿題]
だけでなく、単語の出現回数は、あなたが特別な を開発しますツリーデータ構造。 TreeSetCounterクラスを呼び出します。このようなツリー内のノードは、単語とカウンタで構成される です。手順 が実装されました。
addWord-単語が存在しない場合、単語を追加します。単語 が既にカウンタインクリメント
なる場合は(空ください) - 回数の最も多いが発生している木も、
getMaxFrek()-return単語になります。 どのようにして最も効果的に行うことができますか?
iterator() - イテレータをツリーに返します。これは、アルファベット順に のツリーを印刷するために使用されます。
バランスツリーの実装を出発点として使用します。 ファイルを読み込んで、各単語の単語と出現回数の両方を で表示するプログラムを作成します。
私はどのように私はこれを実装する必要がありますアイデアを与えることができますどのような方法は、最速の木全体をトラバースし、最大見つける?
ツリー追加コード:
/**
* Insert into the tree.
* @param word the item to insert.
* @freq increment if word is already present.
*/
public void addWord(String name) {
root = addWord(name,root);
}
/**
* Internal method to insert into a subtree.
* @param word the item to insert.
* @param t the node that roots the tree.
* @return the new root.
* @freq increment if word is already present.
*/
protected Node addWord(String word, Node t)
{
if(t == null)
t = new Node(word);
else if(word.compareTo(t.word) < 0)
t.left = addWord(word, t.left);
else if(word.compareTo(t.word) > 0)
t.right = addWord(word, t.right);
else
t.freq++;
return t;
}
仕事をdoesntのgetMaxFreq ...私は事前にNullPointerExceptionがに
private Node getMaxFreq(Node node){
Node temp = null;
if(node.left != null){
if(node.compareTo(getMaxFreq(node.left)) > 0){
temp = node;
}
else{
temp = node.left;
}
}
if(node.right != null){
if(node.compareTo(getMaxFreq(node.right)) > 0){
temp = node;
}
else{
temp = node.right;
}
}
return temp;
}
感謝を入手します!
アルファベット順にツリーのバランスが取れている場合、最大値はツリー内のどこでもかまいません。それで、O(n)よりも速くすることをどのように期待しますか?おそらく、周波数を追跡するために別のデータ構造が必要になるでしょう。 – aioobe
@aioobe 私は提案があります – JohnBanana
これは宿題のように聞こえますが、私はこれの制約や目標を知らない。しかし、[max-heap](https://en.wikipedia.org/wiki/Heap_%28data_structure%29)として実装された優先度キューを作るのはどうですか? – aioobe