输出二叉树所有路径
输入:
dic = {
"title": "a",
"children": [
{
"title": "b",
"children": [
{"title": "c"}
]
},
{
"title": "d",
"children": [
{
"title": "e",
"children": [
{"title": "f"}
]
},
{
"title": "g",
"children": [
{"title": "h"}
]
}
]
}
]
}
输出:
[['a', 'b', 'c'], ['a', 'd', 'e', 'f'], ['a', 'd', 'g', 'h']]
思路:深度优先+二分法+递归
代码:
def dict_to_list(dic: dict, path_list=None):
if not path_list:
path_list = [[]]
path_list[-1].append(dic.get("title"))
if "children" not in dic:
return path_list
else:
children_list = dic.get("children")
if len(children_list) < 1:
return path_list
elif len(children_list) == 1:
child_left = children_list[0]
return dict_to_list(child_left, path_list)
else:
child_left = children_list[0]
child_right = children_list[1]
path_list_buffer = list()
path_list_buffer.extend(path_list[-1])
path_list = dict_to_list(child_left, path_list)
path_list.append(path_list_buffer)
path_list = dict_to_list(child_right, path_list)
return path_list