我有一个格式的行文本文件
2 0 0
7 0 0
4 1 1
10 0 0
9 0 1
8 1 1
这些行表示二进制搜索树中的数据,其中第一个元素是节点数据,第二个元素是是否存在左子元素(如果不是,则为0,如果是,则为1),第三个是是否是右子元素子级存在(如果否则为0,如果是则为1)
我有一个名为“ BinarySearchTree”的类,该类具有以下初始化函数
def __init__(self, value=None):
# Initializes the tree with a value node, a left child and a right child
self.leftChild = None
self.rightChild = None
self.height = 1
self.value = value
我还有一个带有以下“推”和“弹”功能的堆栈类:
def push(self, item):
# Adds an item to the beginning of the stack
ending = self.stack
self.stack = [item] + [ending]
def pop(self):
# Removes and returns the first element from the stack
if self.isEmpty():
return None
top_element = self.stack[0]
self.stack = self.stack[1:]
return top_element
我正在尝试从文本文件中的行并使用堆栈类创建一个二进制搜索树实例。到目前为止,我有:
def loadTreeFromFile(filename):
binarySearchTree = stack.Stack()
with open(filename) as file:
# gets a list containing only the elements in the txt file
for level in file.readlines():
nodeInfo = level.rstrip().split()
data, lc, rc = int(nodeInfo[0]), int(nodeInfo[1]), int(nodeInfo[2])
print(data, lc, rc)
if rc == 1:
right_tree = binarySearchTree.pop()
if lc == 1:
left_tree = binarySearchTree.pop()
newTree = BinarySearchTree(data)
if rc == 1:
newTree.rightChild = right_tree
if lc == 1:
newTree.leftChild = left_tree
binarySearchTree.push(newTree)
return newTree
当我尝试显示BST时遇到问题,我得到8: [[[<__main__.BinarySearchTree object at 0x1033e4390>, []]], 9: [None, 10: [None, None]]]
(我为BST类编写了显示功能,所以这不是问题),当我尝试使用BST类执行任何操作时这个新创建的BST(例如获取深度,对其进行搜索等),我得到了错误。非常感谢您的任何帮助。