0

基本上我希望能够让树类型的每个节点都有一个数据字段和一个分支列表。此列表应包含许多 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)
4

3 回答 3

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. 不确定这是否是您想要的。您想要列表的一层中的所有叶子吗?(如果是这样,必须修改源代码。)
于 2012-04-30T19:38:41.867 回答
0

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

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

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

您的其余代码看起来不错。

于 2012-04-30T21:06:49.187 回答
0

是这self.root棵树的父母吗?在这种情况下,如果它没有分支 ( ) 则getLeaves()应该返回,而不是像你在那里一样。此外,如果您确实有子分支,则应包含在.selflen(self.branches)==0self.rootselfbranchSum

于 2012-04-30T18:59:06.963 回答