返回修改后的树,并在每个节点上添加方括号

时间:2019-07-07 12:16:07

标签: python recursion data-structures tree tuples

我有一个遍历树中每个节点的函数,我正在尝试创建一个修改过的树,并在每个节点上添加了括号。

由于元组是不可变的,我知道我无法按索引选择节点并以这种方式添加方括号,因此我一直在尝试思考如何将树重构回其原始状态,并在每个节点周围加上方括号。

def add_brackets(node):
  parent, children = node
  for child in children:
    add_brackets(child)

为此,

("hello", (("a", ()), ("b", (("cde", ()), ("fg", ())))))

我想回来,

('[hello]', (('[a]', ()), ('[b]', (('[cde]', ()), ('[fg]', ())))))

我该怎么做?

1 个答案:

答案 0 :(得分:2)

是的,元组是不可变的,您需要构造新的元组并返回它们。

尝试一下:

def add_brackets(node):
    parent, children = node
    new_parent = "[{}]".format(parent)
    new_children = tuple(add_brackets(child) for child in children)
    return (new_parent, new_children)


root = ("hello", (("a", ()), ("b", (("cde", ()), ("fg", ())))))
root = add_brackets(root)
print(root)

输出:

('[hello]', (('[a]', ()), ('[b]', (('[cde]', ()), ('[fg]', ())))))