簡體   English   中英

如何打印在Python中實現為子樹列表的樹的葉子?

[英]How to print leaves of a tree implemented as a list of subtrees in Python?

基本上,我希望能夠使樹類型的每個節點都有一個數據字段和一個分支列表。 該列表應包含許多Tree類型的對象。 我認為我已經實現了列表的實際實現,但是當我嘗試使用getLeaves方法時,卻得到了奇怪的行為。 基本上,它以遞歸方式調用自身,並且永遠不會返回,並且發生的方式是樹的第二個節點以某種方式將其第一個分支設置為自身(我認為)。

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)

self.root是所述樹的父級嗎? 在這種情況下,如果沒有分支( len(self.branches)==0 ),則getLeaves()應該返回self ,而不是您在那里擁有的self.root 另外,如果您確實有子分支,則應將self包含在branchSum

可能的解決方案(您的源代碼進行了很小的更改):

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. 不太確定這是否是您想要的。 您是否希望所有葉子都在列表的一級? (如果是這樣,則必須修改源代碼。)

您的“ branches”變量是類成員,而不是實例成員。 您需要在構造函數中初始化“分支”實例變量:

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

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

您的其余代碼看起來不錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM