2017-11-29 8 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를 반환하도록되어 : 여기

는 코드입니다. 두 경우 모두 그렇게되지는 않습니다. 오류 메시지는 다음과 같습니다 거기에 몇 가지 문제가, buscar에 포함 된 주석을 참조

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

답변

1

:

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