从根到叶的所有可能方式的列表(无二叉树)

2024-10-03 17:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着列出从树的根到叶子的所有可能的移动。我目前有它的设置,所以我可以得到一个列表 ['A',['B',['C'],['K'],['D',['E',['F'],['G'],['H',['I'],['J']]

以下是列表所代表的内容的图像:

list representation

我只是想知道如何将上面的列表转换为: “ABK”,“ABC”,“ADEF”,“ADEG”,“ADHI”,“ADHJ”

我试过在列表中递归,但我不太明白。顺便说一句,我尝试使用列表的唯一原因是因为这是我能想到的唯一真实的方法,而且它似乎没有从列表中延伸到不同的路径?你知道吗


Tags: 方法图像路径内容列表原因代表abc
1条回答
网友
1楼 · 发布于 2024-10-03 17:16:56

这里有一个建议!你知道吗

def walktree(lst):
    # Is it a leaf?  Here's our base case.
    if len(lst) == 1:
        return lst

    # If not, then it's a node; just make sure the list is formatted correctly.
    assert(len(lst) == 3)

    first = lst[0]

    # Here's where the recursion happens. 
    left = walktree(lst[1])
    right = walktree(lst[2])

    # Finally, the combination step. 
    return [first + x for x in left + right]

相关问题 更多 >