函数searchNode无法正常工作。搜索二叉树中的元素时,它返回None而不是True。我不明白为什么它是None,因为它应该返回True或False但从不返回None。你能告诉我如何解决它吗?
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
self.visited = 0
def insert(self,value):
if self.root is None:
self.root = Node(value)
else:
self.insertNode(self.root, value)
def insertNode(self,current, value):
if value <= current.value:
if current.left:
self.insertNode(current.left, value)
else:
current.left = Node(value)
else:
if current.right:
self.insertNode(current.right, value)
else:
current.right = Node(value)
def fromArray(self, newarr):
for each in newarr:
self.insert(each)
return
def search(self, value):
self.visited = 0
self.searchNode(self.root, value)
def searchNode(self,current,value):
if (current is None):
return False
elif (value == current.value):
return True
elif (value < current.value):
self.visited += 1
return self.searchNode(current.left, value)
else:
self.visited += 1
return self.searchNode(current.right, value)
答案 0 :(得分:0)
你永远不会在search
中返回任何内容。您可能希望return self.searchNode(self.root, value)
而不是仅仅调用它。