我有一个用于从一组节点构建树的函数
def buildTree(self, nodeList,):
if len(nodeList) > 1:
nodeList = sorted(nodeList, key=self.getKey)
newNode = self.makeNode(nodeList[0], nodeList[1])
nodeList.pop(0)
nodeList.pop(0)
nodeList.append(newNode)
nodeList = self.buildTree(nodeList)
else:
print type(nodeList[0])
return nodeList[0]
输出类型'实例'
from TreeFactory import TreeFactory
nodeList = builder.buildNodeList(
'the quick brown fox jumped over the lazy dog')
nodeHead = builder.buildTree(nodeList)
print type(nodeHead)
当我从构建器打印返回类型时,我得到"键入' NoneType'"打印出来
那么为什么它在返回之前是一个有效的实例,而不是之后呢?
答案 0 :(得分:1)
根据https://stackoverflow.com/users/367273/npe,问题是if分支没有返回任何内容,因此递归导致nodeList填充None值。通过更改buildTree函数使其读为
def buildTree(self, nodeList,):
if len(nodeList) > 1:
nodeList = sorted(nodeList, key=self.getKey)
newNode = self.makeNode(nodeList[0], nodeList[1])
nodeList.pop(0)
nodeList.pop(0)
nodeList.append(newNode)
nodeList = self.buildTree(nodeList)
return nodeList
else:
return nodeList[0]
解决了这个问题。