插入不持久的内容

2024-10-04 03:28:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现一个BST,并且正在处理insert。我希望能够调用一些简单的东西,比如tree.insert(Node(1))。但问题是binaryInsert不会持续下去。实现此功能的最佳方式是什么

class Node:
    def __init__(self, data):
        self.value = data
        self.rightChild = None
        self.leftChild = None

class Tree:
    def __init__(self):
        self.root = None

    def binaryInsert(self, root, node):
        if root == None:
            root = node
        else:
            if root.value > node.value:
                if root.leftChild == None:
                    root.leftChild = node                   
                else:
                    self.binaryInsert(root.leftChild, node)
            else:
                if root.rightChild == None:
                    root.rightChild = node                  
                else:
                    self.binaryInsert(root.rightChild, node)

    def insert(self, node):
        self.binaryInsert(self.root, node)

Tags: selfnonenodeifinitvaluedefroot
1条回答
网友
1楼 · 发布于 2024-10-04 03:28:06

从代码中考虑这些行:

def binaryInsert(self, root, node):
    if root == None:
        root = node

在这里,您只是重写了一个局部根变量(作用域为方法),我已经更正了您的代码,请随意提问:

class Node:
    def __init__(self, data):
        self.value = data
        self.rightChild = None
        self.leftChild = None

class Tree:
    def __init__(self):
        self.root = None

    def binaryInsert(self, tree, node):
        if tree.root == None:
            tree.root = node
        else:
            if tree.root.value > node.value:
                if tree.root.leftChild == None:
                    tree.root.leftChild = node                   
                else:
                    self.binaryInsert(tree.root.leftChild, node)
            else:
                if tree.root.rightChild == None:
                    tree.root.rightChild = node                  
                else:
                    self.binaryInsert(tree.root.rightChild, node)

    def insert(self, node):
        self.binaryInsert(self, node)

相关问题 更多 >