2012-04-30 38 views
0

基本上我希望能够让类型树的每个节点都有一个数据字段和一个分支列表。该列表应该包含许多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) 

回答

0

self.root该树的父亲?在这种情况下,getLeaves()应该返回self,如果它没有分支(len(self.branches)==0)而不是self.root,则应该返回self。此外,如果您有子分行,则应在branchSum内包含self

0

可能的解决方案(你的源代码的微小变化):

class Tree: 
    def __init__(self, data): 
     """Basic tree graph datatype""" 
     self.data = data 
     self.branches = [] 

    def addBranch (self, addition): 
     """Adds another object of type Tree as a branch""" 
     self.branches.append(addition) 

    def getLeaves (self): 
     """returns the leaves of a given branch. For 
      leaves of the tree, specify data""" 
     if len(self.branches) == 0: 
      return self.data 
     else: 
      branchSum = [] 
      for b in self.branches: 
       branchSum.append(b.getLeaves()) 
      return branchSum 

## Use it 

t0 = Tree("t0") 
t1 = Tree("t1") 
t2 = Tree("t2") 
t3 = Tree("t3") 
t4 = Tree("t4") 

t0.addBranch(t1) 
t0.addBranch(t4) 
t1.addBranch(t2) 
t1.addBranch(t3) 

print(t0.getLeaves()) 

输出:

[['t2', 't3'], 't4'] 

备注:

  1. 看起来有些格式化您的代码打破。
  2. 不太确定这是你想要的。你想要所有的叶子在列表的一个级别? (如果是的话源代码必须改编)
0

你的'分支'变量是一个类成员,而不是一个实例成员。您需要在构造函数中初始化“分支”实例变量:

class Tree: 
    """Basic tree graph datatype""" 

    def __init__(self, root): 
     self.branches = [] 
     self.root = root 

其余代码看起来不错。