二叉树AttributeError:“NoneType”对象没有属性“insertRight”

2024-10-03 02:33:51 发布

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

我一直在读这本书here,我正试图完成最后一个要求您构建二叉树的练习。但是我很难理解树项是如何添加的。在

这里是BinaryTree类:

  class BinaryTree(object):
        def __init__(self, rootObj):
            self.key = rootObj
            self.leftChild = None
            self.rightChild = None

        def insertLeft(self, newNode):
            if self.leftChild == None:
                self.leftChild = BinaryTree(newNode)
            else:
                t = BinaryTree(newNode)
                t.leftChild = self.leftChild
                self.leftChild = t

        def insertRight(self, newNode):
            if self.rightChild == None:
                self.leftChild = BinaryTree(newNode)
            else:
                t = BinaryTree(newNode) # make a new BinaryTree first
                t.rightChild = self.rightChild
                self.rightChild = t 

        def getRightChild(self):
            return self.rightChild

        def getLeftChild(self):
            return self.leftChild

        def setRootVal(self, obj):
            self.key = obj 

        def getRootVal(self):
            return self.key

当我尝试向树中添加项时,它们并没有真正做到我所期望的。在

例如,如果我执行以下代码:

^{pr2}$

最后一行导致AttributeError: 'NoneType' object has no attribute 'insertRight' 为什么这条线导致了这个错误?为什么第三行不出错?在


Tags: keyselfnoneobjreturnifobjectdef
1条回答
网友
1楼 · 发布于 2024-10-03 02:33:51

您的insertRight方法在左侧插入

def insertRight(self, newNode):
    if self.rightChild == None:
        self.leftChild = BinaryTree(newNode)
        #    ^^^^

因此,所有的rightChild属性将永远保留None。在

您应该使用is来测试None

^{pr2}$

相关问题 更多 >