我的二叉搜索树方法插入有什么问题?

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)

我向二叉搜索树中插入了一些节点,但是二叉树的所有节点仍然是None。有没有人可以帮我解决这个问题?谢谢

root = node 只是在 root 引用其他内容。 root 不再引用传入的对象。它不会更改传入的对象。而是说 for k,v in vars(node).items(): setattr(root, k, v)

您混淆了参考资料。

如果你实例化你的 BST,你就使它的根成为 Node()。绝对正确。插入时,您检查此节点的值(在第一步中)。还可以。然后,将 Node 的新实例分配给 local 变量,此后您将无法访问该变量。

另外,你新建Node的逻辑也不对。在测试其值之前,您必须检查 root 本身是否为 None。否则,你永远不会 children ;_;

这是您的解决方法:

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)