将树路径存储在数组中

时间:2019-07-16 23:23:41

标签: tree

array = []
arrays = []


all_paths(root, array, arrays)


def all_paths(root, path, paths):
    if root is None:
        return None

    path.append(root.val)

    rleft = all_paths(root.left, path, paths)
    rright = all_paths(root.right, path, paths)

    if rleft is None and rright is None:
        paths.append(",".join(list(map(str,path))))
        #paths.append(path)

    path.pop()

    return root

我正在尝试从树的根到叶的所有路径作为列表列表。 上面的函数可以存储在paths变量中,并像下面这样给我正确的输出

['6,2,0', '6,2,4,3', '6,2,4,5', '6,8,7', '6,8,9'] 

但是如果我用paths.append(path)代替paths.append(",".join(list(map(str,path)))),我会跌倒

[[], [], [], [], []]

我在做什么错了,如果我希望将列表列表作为输出,其中每个列表都是叶路径的根,我应该怎么做

很抱歉,问题是否太幼稚。树木不好。

0 个答案:

没有答案