2017-11-29 15 views
1

スペイン語のBST(バイナリ検索ツリー)またはABBに問題があります。BSTのbuscar機能のエラー

私の問題は、以下のコードでスペイン語のsearch()またはbuscar()という機能が動作しないということです。私は何が間違っているのか分からない。

#TAD de Árbol Binario de Búsqueda 
 
class ABB(object): 
 
\t def __init__(self, data): 
 
\t  self.right = None 
 
\t \t self.left = None 
 
\t \t self.data = data 
 

 
\t def insert(self, data): 
 
\t \t if self.data: 
 
\t \t \t if data < self.data: 
 
\t \t \t \t if self.left == None: 
 
\t \t \t \t \t self.left = ABB(data) 
 
\t \t \t \t else: 
 
\t \t \t \t \t self.left.insert(data) 
 
\t \t \t elif data > self.data: 
 
\t \t \t \t if self.right == None: 
 
\t \t \t \t \t self.right = ABB(data) 
 
\t \t \t \t else: 
 
\t \t \t \t \t self.right.insert(data) 
 
\t \t else: 
 
\t \t \t self.data = data 
 

 
\t def buscar(self, x): 
 
\t \t while x != self.data and self.data != None: 
 
\t \t \t if self.data < x: 
 
\t \t \t \t self.left.buscar(x) 
 
\t \t \t else: 
 
\t \t \t \t self.right.buscar(x) 
 
\t \t if self.data == x: 
 
\t \t \t return True 
 
\t \t if self.data == None: 
 
\t \t \t return False 
 

 
n = ABB(8) 
 
n.insert(3) 
 
n.insert(10) 
 
n.insert(1) 
 
n.insert(6) 
 
n.insert(4) 
 
n.insert(7) 
 
n.insert(14) 
 
n.insert(13) 
 
print("existe?",n.buscar(22))

検索数が存在するかどうtrueまたはfalseを返すことになっている。ここで

はコードです。そして、どちらの場合も、それは起こらない。エラーメッセージは次のとおりです。

AttributeError: 'NoneType' object has no attribute 'buscar' 

答えて

1

いくつかの問題がbuscarであり、埋め込まれたコメントを参照してください:

def buscar(self, x): 
    if x != self.data: 
     if self.data > x: # you should check > x not < x 
      if self.left: # check if the child-node exists before calling recursively 
       return self.left.buscar(x) 
      else: 
       return False 
     else: 
      if self.right: # same for right child 
       return self.right.buscar(x) 
      else: 
       return False 
    if self.data == x: 
     return True 
+0

そんなに友人に感謝。さて、コードは完璧に動いています。ありがとう!!! – Calvin