我正在尝试实现BST,在执行对root
的调用后,它应将None
的值重新设置为insert()
,此时应将其更改为第一个值在第一次调用后插入,然后创建树。关于为什么发生这种情况有什么建议吗?
class Node:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
return str(self.value)
def insert(root,value):
if root is None:
root = Node(value)
print(1)
elif value <= root.value:
root.left = insert(root.left, value)
print(2)
else:
root.right = insert(root.right, value)
print(3)
def search(root,value):
if root is None:
print("False")
elif root.value == value:
print("True")
elif value <= root.value:
return search(root.left, value)
else:
return search(root.right, value)
root = None
insert(root,15)
insert(root,10)
insert(root,25)
search(root,10)
输出:
1
1
1
False
答案 0 :(得分:2)
在函数中进行诸如root = Node(value)
之类的赋值时,它不会像您期望的那样在外部范围内修改root
对象。而是将root
函数内的局部insert
重新分配给新的Node
对象,该对象在函数返回时超出范围。
一种解决方案是返回您创建的新根对象,并在调用范围内将其重新分配,以覆盖旧根的值。这对于递归分配也很重要,因此正确设置.left
和.right
属性。
这是固定代码:
class Node:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
return str(self.value)
def insert(root,value):
if root is None:
root = Node(value)
print(1)
elif value <= root.value:
root.left = insert(root.left, value)
print(2)
else:
root.right = insert(root.right, value)
print(3)
return root
#^^^^^^^^^^
def search(root,value):
if root is None:
print("False")
elif root.value == value:
print("True")
elif value <= root.value:
return search(root.left, value)
else:
return search(root.right, value)
root = None
root = insert(root,15)
#^^^^^^
root = insert(root,10)
root = insert(root,25)
search(root,10)
search(root,15)
search(root,25)
输出:
1
1
2
1
3
True
True
True
尽管我了解您很可能处于调试模式,但我也建议您从函数内部消除打印内容。快速清理:
class Node:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
return str(self.value)
def insert(root,value):
if not root:
root = Node(value)
elif value <= root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
def search(root, value):
if not root:
return False
elif root.value == value:
return True
elif value <= root.value:
return search(root.left, value)
return search(root.right, value)
if __name__ == "__main__":
root = None
root = insert(root, 15)
root = insert(root, 10)
root = insert(root, 25)
root = insert(root, 27)
print(root, root.left, root.right, root.right.right)
print(search(root, 10))
print(search(root, 15))
print(search(root, 25))
print(search(root, 27))
print(search(root, 12))