我正在嘗試製作二叉搜索樹中所有項目的列表。我理解遞歸,但我不知道如何讓它返回每個值,然後將其附加到列表中。我想創建一個名爲makeList()
的函數,它將返回我樹中所有項目的列表。除了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)
尋找我能看到爲什麼它不工作,但我不知道如何使它發揮作用。
編輯
好吧,我知道了!我甚至有兩個答案分別是:
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
重新開始?
我希望這是有道理的。
哈哈你們讓我覺得!我會繼續努力一下,回到你們身邊! – crh878 2011-04-05 02:21:16