【问题标题】:Trying to save node or reference to node in a list尝试在列表中保存节点或对节点的引用
【发布时间】:2020-11-24 21:51:53
【问题描述】:

我有一个树类,其中该类使用数据、左和右属性进行初始化。 在同一堂课中,我有一个“保存”方法。 我正在使用列表作为队列。 我正在尝试创建一个“保存”方法,它只接受一个参数“数据”。 此保存方法的目的是从我的列表中出列,检查该节点以查看其是否为空,如果是,则将我的数据保存在那里。否则,它将该节点的 2 个子节点排入列表。 这样做的目的是将数据按级别顺序保存到树中。 因为类被初始化,所以树中总是至少有 1 个元素是根节点。

我一直遇到的问题是,每当我在 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

【问题讨论】:

  • 请附上您的代码,以便我们更好地帮助您。
  • "很明显,当我尝试..." 是的,很明显 :-) 提炼代码示例怎么样,这样我们就知道你在说什么(并且你的代码做了你想做的事)认为是的)。
  • 是的,我已将代码添加到原始帖子中
  • 您还没有……您已经添加了指向代码图片的链接。请复制代码到问题中(我没有对你投反对票,但请阅读以下内容以了解为什么代码图像不好:idownvotedbecau.se/imageofanexception
  • 我明白了,谢谢你让我知道。我现在已经在正文中附加了代码。

标签: python algorithm tree binary structure


【解决方案1】:

你的代码有几个明显的问题: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)

【讨论】:

  • 我明白了,我在原始帖子中进行了一些更改。在 if 语句中,如果当前节点为空,那么我需要在树中创建一个新节点,我现在已经完成了。这对我来说是一个糟糕的错误。在运行调试器时,我仍然看到项目被添加到队列中,只是整数。因此,当我尝试在 else 语句中附加它们的左/右节点时,它们会失败。是什么原因造成的
  • 在您更新的代码中,您将 temp 放在 if 语句的真正分支中。如果我是你,我会从笔和纸开始,画一个空树,然后画出添加第一个元素所需的操作——你需要在编写问题之前获得概念上的理解。作为调试问题的一个步骤,您应该编写一个打印整个树的函数,以便您可以验证您的代码是否与您使用笔和纸所做的工作相匹配...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
相关资源
最近更新 更多