我正在尝试简化我的一个家庭作业问题并使代码变得更好一点。我正在使用的是二叉搜索树。现在我的函数中有一个Tree()
查找所有元素并将它们放入列表中的类。
tree = Tree()
#insert a bunch of items into tree
然后我使用 makeList() 函数从树中获取所有节点并将它们放入列表中。
要致电makeList()
功能,我做tree.makeList(tree.root)
。对我来说这似乎有点重复。我已经在调用树对象了tree.
so the tree.root
只是浪费一点打字时间。
现在 makeList 函数是:
def makeList(self, aNode):
if aNode is None:
return []
return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)
我想让 aNode 输入一个默认参数,例如aNode = self.root
(这不起作用)这样我就可以用这个来运行该函数,tree.makeList()
.
第一个问题是,为什么这不起作用?
第二个问题是,有没有办法可以实现呢?正如你所看到的makeList()
函数是递归的,因此我无法在函数的开头定义任何内容,否则会出现无限循环。
EDIT这是所要求的所有代码:
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:
self.inOrder(aNode.lChild)
print aNode.data
self.inOrder(aNode.rChild)
def makeList(self, aNode):
if aNode is None:
return []
return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)
def isSimilar(self, n, m):
nList = self.makeList(n.root)
mList = self.makeList(m.root)
print mList == nList