2017-04-12 8 views
0

私の問題は、ツリー内にvalueというノードの深度を返すように求めています。私はdepth(root, 7, 0 [depth initially])をしなかった場合値のバイナリ検索ツリーを持つ特定のノードの深さを返します

例えば、それは2

enter image description here

私の最初の試みを返す必要があり、私はこの

# value is the value wanted, count measures the 'depth' 

def depth(root, value, count): 

    # if we are not at a empty node 
    if root != None: 
     # if we found our data, then just return the count (depth) 
     if root.data == value: 
      return count 


     # otherwise increase count, and traverse both sides 
     else: 
      count += 1 
      count = depth(root.left, value, count) 
      count = depth(root.right, value, count) 


    return count 

のようなもの、私は深さを得るのに、私はこれを実行しました= 6、なぜ私は分かりません

答えて

0

枝の2番目の部分では、必要な時に戻ってきません。

rootで目標値が見つからないとします。次に、左に検索した結果にcountを設定します。次に、左(再び)を検索した結果にcountを設定します。

あなたは決して権利を検索せず、あなたがターゲットを見つけたかどうか(ifから落ちた後)カウントを返します。今すぐあなたの戻り値は、ターゲットが見つかったとき、またはcount「ターゲットを見つけることができなかった」という意味、Noneのどちらかになります

if you match the target: 
    return count 
else: 
    search on the left side. 
    if that is not None, return it. 
    search on the right side. 
    regardless of whether it's None or not, return it. 

より良いアプローチは、になります。途中ダウンの

+0

申し訳ありませんが私の代わりに間違いでした。私は正しい方向に切り替えるつもりでしたが、コードを間違ってコピーしたようです。私はそれを編集しました –

0

なぜcountときにできる方法バックアップのcount

def depth(root, value): 
    # if we are at a empty node return infinity 
    if not root: 
     return float('inf') 

    # if we found our data, then just return 0 
    if root.data == value: 
     return 0 
    # otherwise traverse both sides 
    return 1 + min(depth(root.left, value), depth(root.right, value)) 

は、あなたがあなたの端子ケースとしてreturn Noneして、チェックを実装することができますmin()を取り除くために、それは醜いですし、慣用ない:

def depth(root, value): 
    # if we are at a empty node return None 
    if not root: 
     return None 

    # if we found our data, then just return 0 
    if root.data == value: 
     return 0 

    # otherwise, traverse both sides 
    c = depth(root.left, value) 
    if c is None: 
     c = depth(root.right, value) 
     if c is None: 
      return None 
    return c + 1 

またBFSとしてそれを実装

+0

分は何ですか?どちらの方が近いの? –

+0

どうすればその分を取り除くことができますか?ツリーに一意の値があると仮定して –

+0

値を持たないパスを返すのは何ですか?チェックを実装することも、単に 'min()'を使うこともできますか?別の方法として、キューを使用して幅優先検索を行う方法があります。 – AChampion

関連する問題