python 函数参数self_对象-使用self.xxxx作为默认参数-Python

我试图简化我的一项家庭作业问题,并使代码更好一点。 我正在使用的是二进制搜索树。 现在,我在makeList()类中有一个函数,该函数可以查找所有元素并将它们放入列表中。

tree = Tree()

#insert a bunch of items into tree

然后我使用makeList()函数从树中取出所有节点并将它们放在列表中。要调用makeList()函数,我需要tree.makeList()。对我来说,这似乎有点重复。 我已经用tree.来调用树对象,所以tree.root只是浪费一些输入。

现在,makeList函数为:

def makeList(self, aNode):

if aNode is None:

return []

return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)

我想让aNode输入一个默认参数,例如makeList()(这不起作用),这样我就可以用tree.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:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值