如何获取树的所有子节点

2024-09-27 04:22:10 发布

您现在位置:Python中文网/ 问答频道 /正文

“我的树”具有以下结构:

tree={'0':('1','2','3'), '1':('4'), '2':('5','6'), '3':(), '4':('7','8'), '8':('9','10','11')}

如何编写Python代码来检索特定节点的所有给定子节点?例如,如果我给它节点4,代码应该检索7, 8, 9, 10, 11。对于节点2,它应该检索5, 6,依此类推

这就是我试过的。但我正在寻找一些有效的方法

import queue

tree={'0':('1','2','3'), '1':('4'), '2':('5','6'), '3':(), '4':('7','8'), '8':('9','10','11')}

num = input("what you want ")

q = queue.Queue()

q.put(num)

while not q.empty():
  n = q.get()
  for s in n:
    print(s)
    if s in tree:
      q.put(tree[s])

Tags: 方法代码inimportyoutreeinput节点

热门问题