基本上我希望能够让类型树的每个节点都有一个数据字段和一个分支列表。该列表应该包含许多Tree类型的对象。 我想我有列表的实际实现,但我尝试使用getLeaves方法时出现奇怪的行为。基本上它会递归地调用它自己,并且永远不会返回,并且发生的方式在某种程度上是树的第二个节点获得它自己的第一个分支集(我认为)。如何在Python中打印以树状目录形式实现的树叶?
class Tree:
"""Basic tree graph datatype"""
branches = []
def __init__(self, root):
self.root = root
def addBranch (self, addition):
"""Adds another object of type Tree as a branch"""
self.branches += [addition]
def getLeaves (self):
"""returns the leaves of a given branch. For leaves of the tree, specify root"""
print (len(self.branches))
if (len(self.branches) == 0):
return self.root
else:
branchSum = []
for b in self.branches:
branchSum += b.getLeaves()
return (branchSum)