我有一个树类,在这个树类中,使用data、left和right属性初始化该类。 在同一个类中,我有一个“save”方法。 我正在使用列表作为队列。 我试图创建一个“save”方法,它只接受一个参数“data”。 此保存方法的目的是从我的列表中退出队列,检查该节点是否为空,如果为空,则将我的数据保存在那里。否则,它会将该节点的2个子节点排入列表。 其目的是将数据按级别顺序保存到树中。 因为类被初始化,所以树中至少有一个元素是根节点
我经常遇到的问题是,每当我在save方法的开头将self.data(根节点,而不是我当前试图添加的数据)添加到我的列表中时,它只会将数据保存在那里。 显然,当我尝试附加这个int的左和右子元素时,我会得到一个错误,因为int没有左或右属性
我想知道如何将节点保存在列表中,而不是保存节点上的数据
class Tree():
aqueue = []
def __init__(self, item):
self.item = item
self.leftchild = None
self.rightchild = None
self.aqueue.append(self.item)
def add(self, newitem):
temp = self.myqueue.pop(0)
if temp is None:
temp = Tree(newitem)
else:
self.aqueue.append(temp.leftchild)
self.aqueue.append(temp.rightcild)
temp.add(newitem)
self.aqueue.clear() #this is meant to clear queue of all nodes after the recursions are complete
self.aqueue.append(self.item) #this is meant to return the root node to the queue so that it is the only item for next time
您的代码有几个明显的问题:if和else分支都返回,因此后面的代码永远不会运行,
temp == newitem
是一个等式表达式,但即使它是赋值,它也不会做任何事情:相关问题 更多 >
编程相关推荐