2

バイナリ検索ツリーの横断で再帰的に混乱しています。最後にリストを返す必要があるため、値を保存する方法がないため、ちょうど失われています。下の図に示したように、値を保存するためにどのようなデータstypeが使用されているのかわかりません。私は正しくツリーを移動しているとは思いません。私のコードが正しいかどうかわかりません。Binary検索ツリーの横方向

def inorder(self): 

    print("IN INORDER_______________________________") 
    print("Printing self.value" + str(self.__value)) 
    result = [] 

    if self.__left: 
     print("theres self.left") 
     print(self.__value) 
     #result = result + self.__left 
     #print(result) 
     return self.__left.inorder() 
     result 
     print(result + "RESULTS") 

    if self.__right: 

     print("theres self.right") 
     print(self.__value) 
     return self.__right.inorder() 

    return result 



def test_inorder(self): 
    bt = family_tree() 
    bt.add(15, "jim") 
    bt.add(20, "jamie") 
    bt.add(25, "fred") 
    bt.add(35, "howard") 
    bt.add(30, "kc") 
    x = bt.inorder() 

    expected = '''(15, 'jim'),(20, 'jamie'),(25, 'fred'),(30, 'howard'),(35, 'kc')''' 
    self.assertEquals(str(x), expected) 
    t = family_tree(bt) 
    self.assertEquals(str(t), expected) 
+0

私はあなた 'inorder'方法でそこにいくつかのミスを推測します。 return文の後ろにあるコード(例えば 'if self .__ right'のようなブランチ)は決して実行されません。 printステートメントを除いて、あなたの関数は '' 'のようなものに減らすことができますdef inorder(self): self .__ left:return self .__ left.inorder() elif self .__ right:return self .__ right.inorder() else:return [] '' '正確な答えではありませんが、オブジェクトの他の属性(' self.result'と呼ぶ)を使用して、完了して戻るまで各再帰に格納する必要がある値を追加できますそれ。 – mgc

答えて

3

インオーダーの実装に問題があります。それらを一緒に接続するのではなく値を返します。ここで

はあなたのコードに基づいて、私の実装です:

def inorder(self): 
    result = [] 
    if self.__left: 
     result += self.__left.inorder() 

    result.append(self.__value) 

    if self.__right: 
     result += self.__right.inorder() 

    return result