[Python] 纯文本查看 复制代码
def find_hierarchy(target):
# 构建子节点到父节点的映射字典
data = [
"10001,0",
"10002,10001",
"10003,10001",
"10004,10002",
"10005,10003",
"10006,10004",
"10007,10005",
"10008,10005",
"10009,10006",
"10010,10006",
"10011,10007",
"10012,10008",
"10013,10008",
"10014,10010",
"10015,10010",
]
child_to_parent = {}
for line in data:
child, parent = line.split(',')
child = int(child)
parent = int(parent)
child_to_parent[child] = parent
path = []
current = target
while True:
path.append(current)
parent = child_to_parent.get(current)
if parent == 0:
break
current = parent
# 反转路径以得到从根到目标的顺序
path.reverse()
return ','.join(map(str, path))
# 示例
# print(find_hierarchy(10015)) # 输出:10001,10002,10004,10006,10010,10015
# print(find_hierarchy(10009)) # 输出:10001,10002,10004,10006,10009