如何最好地为我的树类编写__str__方法?

问题描述 投票:-1回答:1

我有一个名为Tree的类:

class Tree:
    def __init__(self, tag, children):
        self.tag = tag
        self.children = children
    def __str__(self):
        pass

这是我班上的一个示例对象:

tree = Tree('A', [Tree('B', [Tree('C', [])]), Tree('D', [Tree('E', [])])])

现在,当我打印树时,我希望它看起来如下:

(A (B C) (D E))

我的想法是遍历嵌套的树并检查,直到找到一个空列表,这告诉我该空列表属于我的树的叶子之一。然后,我从那里向上构建它,并在标签和子元素周围添加括号。

python class methods tree
1个回答
0
投票

一种迭代方法可能会起作用,但是我认为在这里递归更合适。

© www.soinside.com 2019 - 2024. All rights reserved.