基本的には、タイプツリーの各ノードにデータフィールドとブランチのリストを持たせたいと思っています。このリストには、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)