2016-10-31 12 views
-1

photo of my non-recursive code再帰的な方法は、バイナリツリー

こんにちは内の要素の出現箇所の数を取得します。私は再帰形式でこのメソッド(写真内)を書くのに問題があります。この方法は、バイナリ検索ツリー内の所与の要素の発生量を取得する。再帰的にこの問題を解決するには 、私はこのように、同じ名前のプライベートヘルパーメソッドでそれを実装しようとしていた。

public int count(){ 
count = 0; 
if (root == null) 
    return count; 
return count (root.getInfo()); 

private int count(T element){ 
(Basically the same code you see in the photo) 
} 

が、私はオーバーフローエラーになってしまいました。私はこのメソッドを再帰的に構造化する方法を見て、教えていただけますか?

乾杯、ありがとう。

+0

rootは、関数のローカル変数ではありません。これは、エラーの原因になります。再帰関数が必要ですが、理にかなっていないループを使用していて、if条件の中で "root = root.getLeft()"も意味をなさない。 –

答えて

1

暫定的な実装は次のようになります。

public int count(T element, T root){ 
    if(element == null) { 
     return 0; 
    } 
    int count = 0; 
    int compare = element.compareTo(root.getInfo()); 
    if(compare == 0){ 
     count++; 
    } 
    count += count(element, root.getLeft()); 
    count += count(element, root.getRight()); 
    return count; 
} 

count(item, root); 
関連する問題