2012-04-30 5 views
0

基本的には、タイプツリーの各ノードにデータフィールドとブランチのリストを持たせたいと思っています。このリストには、Tree型のオブジェクトが多数含まれている必要があります。 私はリストの実際の実装を持っていると思うが、getLeavesメソッドを使ってみると奇妙な動作が起こる。基本的には、それ自体は再帰的に呼び出され、決して返されません。そして、起こる方法は、何とかツリーの2番目のノードがそれ自身の最初のブランチセットになります(私は思っています)。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()は、の代わりにブランチがない場合(len(self.branches)==0)、selfを返す必要があります。また、子ブランチを持っている場合は、branchSumselfを含める必要があります。

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. これがあなたの望むものなのかどうかは分かりません。すべての葉をリストの1つのレベルに入れたいですか?もしそうなら、ソースコードを適合させる必要があります。
0

あなたのブランチ変数はインスタンスメンバーではなくクラスメンバーです。コンストラクタの 'branches'インスタンス変数を初期化する必要があります。

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

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

残りのコードはよく見えます。

関連する問題