我一直在读这本书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'
为什么这条线导致了这个错误?为什么第三行不出错?在
您的
insertRight
方法在左侧插入:因此,所有的
rightChild
属性将永远保留None
。在您应该使用
^{pr2}$is
来测试None
:相关问题 更多 >
编程相关推荐