问题代码(二叉树的搜索):
def contains(self, value: object) -> bool:
# if the tree is empty
if self.root is None:
return False
else:
if value == self.root.value:
return True
elif value < self.root.value:
if self.root.left is None:
return False
subtree = BST()
subtree.root = self.root.left
subtree.contains(value)
else:
if self.root.right is None:
return False
subtree = BST()
subtree.root = self.root.right
subtree.contains(value)
main:
tree = BST([10, 5, 15])
print(tree.contains(15))
print(tree.contains(-10))
print(tree.contains(15))
debug看不出问题,return一切正常,但是输出结果为
None
None
None
问题:递归的返回值无法传递出外层函数
解决办法:递归调用的时候就要套上return
完整代码如下:
def contains(self, value: object) -> bool:
# if the tree is empty
if self.root is None:
return False
else:
if value == self.root.value:
return True
elif value < self.root.value:
if self.root.left is None:
return False
subtree = BST()
subtree.root = self.root.left
return(subtree.contains(value))
else:
if self.root.right is None:
return False
subtree = BST()
subtree.root = self.root.right
return(subtree.contains(value))