【问题标题】:AttributeError: 'int' object has no attribute 'data'AttributeError:“int”对象没有属性“数据”
【发布时间】:2019-06-12 04:46:46
【问题描述】:

我尝试在 Python3.7 中实现二叉搜索树的一些基本操作。我刚从 Hackerrank 开始编码问题,在 BST 中实现 levelOrder 遍历时遇到了困难。我应该怎么做才能解决这个 AttributeError: 'int' object has no attribute 'data'?

我正在使用队列来解决这个问题,最初,队列将指向根节点,然后检查左右子节点。如果找到,孩子将被追加到队列中,并且该过程继续进行,直到队列为空。我在每次迭代中弹出第一个元素并将其存储在 temp 变量中。这样,我将在树的每一级获得节点。

class Node:
    def __init__(self, data):
        self.data = data
        self.leftChild = None
        self.rightChild = None

    def insert(self, data):
        if self.data is not None:
            if data < self.data:
                if self.leftChild is None:
                    self.leftChild = Node(data)
                else:
                    self.leftChild.insert(data)
            elif data > self.data:
                if self.rightChild is None:
                    self.rightChild = Node(data)
                else:
                    self.rightChild.insert(data)
        else:
            self.data = data

    def traverseLevelOrder(self):
        queue = []
        queue.append(self.data)
        while queue:
            # Print front of queue and remove it from queue
            print(queue[0].data)
            temp = queue.pop(0)

            # Enqueue left child
            if temp.leftChild is not None:
                queue.append(temp.leftChild)

            # Enqueue right child
            if temp.rightChild is not None:
                queue.append(temp.rightChild)


class BST:
    def __init__(self):
        self.rootNode = None

    def insert(self, data):
        if self.rootNode is None:
            self.rootNode = Node(data)
        else:
            self.rootNode.insert(data)

    def traverseLevelOrder(self):
        if self.rootNode is None:
            return
        else:
            self.rootNode.traverseLevelOrder()


bst = BST()
bst.insert(2)
bst.insert(4)
bst.insert(1)
bst.insert(3)
bst.traverseLevelOrder()

代码应该返回下面给出的级别遍历顺序(在一个级别内,它应该先打印左节点,然后是右节点):

2
1
4
3

相反,我遇到以下错误:

Traceback (most recent call last):
    print(queue[0].data)
AttributeError: 'int' object has no attribute 'data'

【问题讨论】:

  • queue.append(self.data) 附加了一个int....

标签: python-3.x


【解决方案1】:

您将一个整数 self.data 附加到队列中,然后尝试使用 queue[0].data 访问整数上的属性,从而引发 AttributeError

相反,将节点本身附加:

queue.append(self)

【讨论】:

    【解决方案2】:
    queue.append(self.data)
    

    你的意思是:

    queue.append(self)
    

    ?

    现在您只是将一个数字添加到队列中,而不是整个对象。

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 2021-11-30
      • 2020-03-26
      • 2013-04-15
      • 2021-01-18
      • 2019-05-30
      • 2021-02-24
      • 2021-08-01
      • 2015-07-06
      相关资源
      最近更新 更多