我正在尝试实现一个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)
从代码中考虑这些行:
在这里,您只是重写了一个局部根变量(作用域为方法),我已经更正了您的代码,请随意提问:
相关问题 更多 >
编程相关推荐