我有一个名为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))
我的想法是遍历嵌套的树并检查,直到找到一个空列表,这告诉我该空列表属于我的树的叶子之一。然后,我从那里向上构建它,并在标签和子元素周围添加括号。
一种迭代方法可能会起作用,但是我认为在这里递归更合适。