我有一個子父元組串列。我想遍歷樹以收集輸入節點的所有孩子。
in_list = [(2,1),(3,2),(4,3),(6,5),(7,4),(8,4)]
現在說我想收集節點 2 的所有孩子。那就是
out_list = [3,4,7,8]
這個問題或其解決方案有什么具體名稱嗎?只需要知道在哪里看。
uj5u.com熱心網友回復:
你需要in_list
像DFS一樣遍歷這些節點,你可以試試這個:
def DFS(path, lst, father):
for (a,b) in lst:
if b == father:
path.append(a)
DFS(path, lst, a)
return path
in_list = [(2,1),(3,2),(4,3),(6,5),(7,4),(8,4)]
res = DFS([], in_list , 2)
print(res)
輸出:
[3, 4, 7, 8]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/347685.html