Questions tagged «tree»

树是一种广泛使用的数据结构,它模拟具有一组链接节点的分层树状结构。



3
使用self.xxxx作为默认参数-Python
我正在尝试简化我的作业问题之一,并使代码更好一点。我正在使用的是二进制搜索树。现在,我的Tree()班级中有一个函数可以查找所有元素并将它们放入列表中。 tree = Tree() #insert a bunch of items into tree 然后我使用makeList()函数从树中取出所有节点,并将它们放入列表中。要调用该makeList()函数,我要做tree.makeList(tree.root)。对我来说,这似乎有些重复。我已经用调用了树对象,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输入一个默认参数,例如aNode = self.root(它不起作用),这样我就可以用来运行该函数tree.makeList()。 第一个问题是,为什么这样不起作用? 第二个问题是,有没有一种方法可以起作用?如您所见,该makeList()函数是递归的,因此我无法在该函数的开头定义任何内容,否则会遇到无限循环。 编辑 这是所有要求的代码: class Node(object): def __init__(self, data): self.data = data self.lChild = None self.rChild = None class …


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.