2012-04-30 1 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()은 이 아닌 지점 (len(self.branches)==0)이없는 경우 self을 반환해야합니다. 또한, 자녀가있는 경우 안에 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 

나머지 코드는 좋아 보입니다.

관련 문제