【问题标题】:AttributeError: 'NoneType' object has no attribute 'data' for binary treeAttributeError:“NoneType”对象没有二叉树的属性“数据”
【发布时间】:2021-09-27 17:05:27
【问题描述】:

我正在制作一棵二叉树。但是每当在比较 temp.data 和变量 val 的 while 循环时,我都会收到此错误:

  "tree.py", line 32, in <module>
  tree.insert(30)
  File "tree.py", line 22, in insert
  if temp.data < val:
  AttributeError: 'NoneType' object has no attribute 'data'

我看到了同样的问题并尝试过,但不确定我在这里做错了什么。二叉树的代码是

class Node:
  def __init__(self, val):
    self.data = val
    self.left = None
    self.right = None

class binaryTree:
  def __init__(self):
    self.root = None

  def insert(self, val):
    if self.root is None:
        self.root = Node(val)
        return
    temp = self.root
    while temp is not None:
        #here I am getting the data
        print(temp.data)

        if (temp.data > val):
            temp = temp.left
        if temp.data < val:
            temp = temp.right
    if temp.data > val:
        temp.left = Node(val)
    else:
        temp.right = Node(val)
tree = binaryTree()
tree.insert(50)
tree.insert(30)
tree.insert(20)

即使在打印时,我也能正确获取数据并且输入也很好。 提前致谢。

【问题讨论】:

    标签: python binary-tree nonetype


    【解决方案1】:
            if (temp.data > val):
                temp = temp.left
            if temp.data < val:
                temp = temp.right
    

    在第一个条件成功并且您设置 temp = temp.left 后,temp 现在是 None 所以 if temp.data &lt; val: 失败。将第二个if 更改为elif

    【讨论】:

    • 那是真的谢谢好友
    【解决方案2】:

    起初我以为发生了这个错误是因为您将Node.leftNode.right 初始化为None,然后将这些值分配给temp,然后再为它们分配实际值。

    但现在我认为temp 在您的while 循环之后将始终为None

        while temp is not None:
            if (temp.data > val):
                temp = temp.left
            if temp.data < val:
                temp = temp.right
    <<<< AT THIS POINT, temp will always be None, otherwise the while loop would not have stopped
    

    然后if temp.data &gt; val 尝试访问Nonedata 属性,这会导致错误。 (There is only a single None object 所以写temp.data 等价于写None.data)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2019-01-01
      • 2021-12-26
      • 2019-07-23
      • 2018-05-13
      • 2020-09-07
      相关资源
      最近更新 更多