如何打印在Python中实现为子树列表的树的叶子?

2024-10-01 17:40:36 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我希望每个树型节点都有一个数据字段和一个分支列表。此列表应包含许多树类型的对象。 我想我已经完成了列表的实际实现,但是当我尝试使用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)

Tags: oftheselfbranchtree列表节点def
3条回答

self.root是所述树的父级吗?在这种情况下,getLeaves()应该返回self,如果它没有分支(len(self.branches)==0),而不是{},那么它应该返回{}。另外,如果有子分支,则应该在branchSum中包含self。在

可能的解决方案(您的源代码稍作修改):

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())

输出:

^{pr2}$

备注:

  1. 代码中的某些格式已损坏。在
  2. 不确定这是不是你想要的。你想把所有的叶子都放在一个级别的列表中吗?(如果是这样,源代码必须进行调整。)

“branches”变量是类成员,而不是实例成员。您需要在构造函数中初始化“branchs”实例变量:

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

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

剩下的代码看起来不错。在

相关问题 更多 >

    热门问题