[英]what's wrong with my method insert of binary search tree?
from random import randint
class Node:
def __init__(self, value=None, left_child=None, right_child=None):
self.value = value
self.left_child = left_child
self.right_child = right_child
class BinarySearchTree:
def __init__(self):
self.root = Node()
def __str__(self):
return 'bst'
def insert(self, root, value):
if root.value is None:
node = Node(value)
root = node
else:
if value < root.value:
self.insert(root.left_child, value)
else:
self.insert(root.right_child, value)
bst = BinarySearchTree()
data = []
for i in range(100):
data.append(randint(0,100))
bst.insert(bst.root, data[i])
print(bst.root.value)
I insert some nodes to the binary search tree, but all nodes of binary tree are still None. 我将一些节点插入二叉搜索树,但是二叉树的所有节点仍然为None。 Are there anyone who can help me figure this out?
有谁可以帮助我解决这个问题? Thanks.
谢谢。
Saying root = node
is just making root
reference something else. 说
root = node
只是使root
引用其他东西。 The object that was passed in is just no longer being referenced by root
. 传入的对象不再由
root
引用。 It does not change the object that was passed in. Instead, say for k,v in vars(node).items(): setattr(root, k, v)
它不会更改传入的对象。相反,
for k,v in vars(node).items(): setattr(root, k, v)
说for k,v in vars(node).items(): setattr(root, k, v)
You are mixing up your references. 您正在混淆您的参考。
If you instantiate your BST, you make its root a Node()
. 如果实例化BST,则将其根
Node()
。 Absolutely right. 绝对正确。 When inserting, you check for the value of this node (in the first step).
插入时,请检查该节点的值(在第一步中)。 Still okay.
还可以 Then, you assign a new instance of
Node
to a local variable, which you will not be able to access afterwards. 然后,您将
Node
的新实例分配给本地变量,此后您将无法访问该实例。
In addition, your logic of creating new Node
s is improper. 另外,您创建新
Node
的逻辑是不正确的。 You must check for root itself to be None
before testing its value. 在测试其值之前,必须先将root本身检查为
None
。 Otherwise, you'll never make children ;_; 否则,您将永远不会生孩子;
Here's your fix: 这是您的解决方法:
class Node:
def __init__(self, value=None, left_child=None, right_child=None):
self.value = value
self.left_child = left_child
self.right_child = right_child
class BinarySearchTree:
def __init__(self):
self.root = Node()
def __str__(self):
return 'bst'
def insert(self, root, value):
if root is None:
root = Node()
if root.value is None:
root.value = value
else:
if value < root.value:
self.insert(root.left_child, value)
else:
self.insert(root.right_child, value)
if __name__ == '__main__':
bst = BinarySearchTree()
data = []
for i in range(100):
data.append(randint(0,100))
bst.insert(bst.root, data[i])
print(bst.root.value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.