BST中功能巴士车出错

问题描述 投票:1回答:1

我有BST(二进制搜索树)或西班牙语ABB的问题。

我的问题是,下面的代码中的西班牙语函数search()buscar()不起作用。我不知道我做错了什么。

这是代码:

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

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

	def buscar(self, x):
		while x != self.data and self.data != None:
			if self.data < x:
				self.left.buscar(x)
			else:
				self.right.buscar(x)
		if self.data == x:
			return True
		if self.data == None:
			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'
python-3.x binary-search-tree
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.