python - 转换二叉树中的嵌套列表的列表

标签 python list tree binary-search-tree

在 python 中,我有一个代表二叉树的嵌套列表列表:

L = [0, [[1, [2, 3]], [4, [5, 6]]]]

所以树可以如下所示:

        0
       /  \
      1    4
     /\    /\ 
    2  3  5  6

我现在想要实现一个函数,该函数将树的级别作为输入并返回该级别的所有节点:

GetNodes(0) = 0
GetNodes(1) = [1,4]
GetNodes(2) = [2,3,5,6]

有没有一种简单的方法可以做到这一点,避免对 L 的所有嵌套列表进行残酷搜索? python 中是否有可能对二叉树进行更标准的管理,也许可以将我的列表列表转换为其他内容?

最佳答案

我的解决方案将解析为字典

l = [0, [[1, [2, 3, [[7,8], [10,11]]]], [4, [5, 6, [9,10]]]]]
datadict = {}

def toTree(data,depth=0):
    for elem in data:
        if not isinstance(elem, int):
            toTree(elem, depth+1)
        else:
            d = depth - 1 if depth > 0 else depth
            if datadict.get(d):
                datadict[d] = datadict[d] + [elem]
            else:
                datadict[d] = [elem]

toTree(l)
print(datadict)

输出将是

{0: [0], 1: [1, 4], 2: [2, 3, 5, 6], 3: [9, 10], 4: [7, 8, 10, 11]}

你可以使用 datadict.get(2) 来获取 [2, 3, 5, 6]

关于python - 转换二叉树中的嵌套列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41564604/

相关文章:

java - 在 Java 中将带有列表值的映射转换为列表

algorithm - 大用户事件序列到树

sql - 将平面表解析为树的最有效/优雅的方法是什么?

python - BeautifulSoup - 如何找到第三个连续的 div

python - PyQt:将信息从 GUI 发送到线程

python - 导入 PIL,更具体地说是来自 PIL 的图像,不起作用

c++ - 我应该使用哪种数据结构

python - 打印第 n 行的 pandas 数据框

Python- For Loop - 增加列表中每个元组的每个索引位置

python - 如何在特定字符之前拆分字符串?