在 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/