簡體   English   中英

我的二進制搜索樹方法插入有什么問題?

[英]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)for k,v in vars(node).items(): setattr(root, k, v)

您正在混淆您的參考。

如果實例化BST,則將其根Node() 絕對正確。 插入時,請檢查該節點的值(在第一步中)。 還可以 然后,您將Node的新實例分配給本地變量,此后您將無法訪問該實例。

另外,您創建新Node的邏輯是不正確的。 在測試其值之前,必須先將root本身檢查為None 否則,您將永遠不會生孩子;

這是您的解決方法:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM