深度搜索算法(python实现)获取所有叶子节点到根节点的路径
1. 目标
对于下图中的树结构,遍历输出所有叶子节点到根节点的路径。
2. 实现方式
Python代码如下:
# -*- coding: utf-8 -*-
import pandas as pd
def get_path(start, child_father_dict):
"""
从叶子节点出发,不断向根节点遍历,得到所有叶子节点到根节点的路径
:param start:
eg: 'c'
:param child_father_dict:
eg: {'c': {'d', 'b'}, 'd': {'a'}, 'b': {'a'}}
:return: all_path:
eg: [[['c', 'b', 'a'], ['c', 'd', 'a']]]
"""
def _dfs(node, path, res):
path.append(node)
if node not in child_father_dict:
res.append(path.copy())
path.pop()
return