Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 二叉树属性错误:';非类型';对象没有属性';insertRight';_Python_Class_Python 2.7_Tree_Binary Tree - Fatal编程技术网

Python 二叉树属性错误:';非类型';对象没有属性';insertRight';

Python 二叉树属性错误:';非类型';对象没有属性';insertRight';,python,class,python-2.7,tree,binary-tree,Python,Class,Python 2.7,Tree,Binary Tree,我一直在读这本书,我正在努力完成最后一个练习,这个练习要求你建立一个二叉树。然而,我很难理解树项目是如何添加的 下面是BinaryTree类: class BinaryTree(object): def __init__(self, rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def

我一直在读这本书,我正在努力完成最后一个练习,这个练习要求你建立一个二叉树。然而,我很难理解树项目是如何添加的

下面是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
当我尝试向树中添加项时,它们并没有真正实现我的期望

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

a = BinaryTree('a')
a.insertLeft('b')
a.getLeftChild().insertRight('c')
a.insertRight('w')
a.getRightChild().insertRight('x')   #this one raises an error
最后一行导致一个
AttributeError:'NoneType'对象没有属性'insertRight'

为什么这一行会导致此错误?为什么第三行没有出现错误?

您的
insertRight
方法在左侧插入:

def insertRight(self, newNode):
    if self.rightChild == None:
        self.leftChild = BinaryTree(newNode)
        #    ^^^^
因此,您的所有
rightChild
属性将永远保持
None

您应该使用
is
测试
None

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