기본적으로 유형 트리의 각 노드에 데이터 필드와 분기 목록이 있어야합니다. 이 목록은 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)