我正在尝试列出二叉搜索树中的所有项目.我理解递归,但我不知道如何使它返回每个值,然后将其附加到列表中.我想创建一个名为makeList()的函数,它将返回树中所有项的列表.除了makeList()函数之外,我的程序中的所有函数都可以工作,并且包含它们以确保每个人都理解我如何设置树的基本结构.
class Node(object):
def __init__(self, data):
self.data = data
self.lChild = None
self.rChild = None
class Tree(object):
def __init__(self):
self.root = None
def __str__(self):
current = self.root
def isEmpty(self):
if self.root == None:
return True
else:
return False
def insert (self, item):
newNode = Node (item)
current = self.root
parent = self.root
if self.root == None:
self.root = newNode
else:
while current != None:
parent = current
if item < current.data:
current = current.lChild
else:
current = current.rChild
if item < parent.data:
parent.lChild = newNode
else:
parent.rChild = newNode
def inOrder(self, aNode):
if aNode == None:
pass
if aNode != None:
self.inOrder(aNode.lChild)
print aNode.data
self.inOrder(aNode.rChild)
def makeList(self, aNode):
a = []
self.inOrder(aNode)
a += [aNode.data]
print a
n = Tree()
for i in [4,7,2,9,1]:
n.insert(i)
n.makeList(n.root)
看看我的makeList()函数,我可以看到为什么它不起作用,但我不知道如何让它工作.
编辑
好,我知道了!我甚至得到了两个答案:
def makeList(self, aNode, a = []):
if aNode != None:
self.makeList(aNode.lChild, a)
a += [aNode.data]
self.makeList(aNode.rChild, a)
return a
和
def makeList2(self, aNode):
if aNode is None:
return []
return self.makeList2(aNode.lChild) + [aNode.data] + self.makeList2(aNode.rChild)
回头看,我可以看到我不太了解递归,所以是时候打书了!任何人都有很好的递归资源?
另一个问题,所以说我调用了我的makeList()函数.当Python通过makeList()时,当它到达self.makeList(aNode.lChild,a)时它会在它仍然完成makeList()函数时再次开始运行该函数,或者一切都停止并且它刚刚重新开始它是新的aNode?
我希望这是有道理的.
解决方法:
你真是太近了! makeList非常简单:
def makeList(self, aNode):
if aNode is None:
# Stop recursing here
return []
return self.makeList(aNode.lChild) + [aNode.data] + self.makeList(aNode.rChild)
基本上,请确保您没有尝试递归过去的空节点.然后返回左树的列表,当前节点和右树的列表.
标签:python,binary-search-tree 来源: https://codeday.me/bug/20190704/1381583.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。