Python 二叉树属性错误:';非类型';对象没有属性';insertRight';
我一直在读这本书,我正在努力完成最后一个练习,这个练习要求你建立一个二叉树。然而,我很难理解树项目是如何添加的 下面是BinaryTree类: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
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