【输出二叉树所有路径】

输出二叉树所有路径


输入:

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值