试图在列表中保存节点或对节点的引用

2024-04-23 20:01:57 发布

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

我有一个树类,在这个树类中,使用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

Tags: the数据方法selfnone列表data节点
1条回答
网友
1楼 · 发布于 2024-04-23 20:01:57

您的代码有几个明显的问题:if和else分支都返回,因此后面的代码永远不会运行,temp == newitem是一个等式表达式,但即使它是赋值,它也不会做任何事情:

def add(self, newitem):
    temp = self.myqueue.pop(0)
    if temp == None:       # should use temp is None
        temp == newitem    # temp = newitem still wouldn't do anything
        return True
    else:
        self.aqueue.append(temp.leftchild)
        self.aqueue.append(temp.rightcild)
        return temp.add(newitem)
    
    # you will never get here, since both branches of the if returns
    self.aqueue.clear()            # delete everything in the list..?
    self.aqueue.append(self.item)

相关问题 更多 >