-1

我是 Python 新手,正在尝试构建一个基于字符的BFS 树来打印父子关系。一个密切相关的解决方案,但它是一个基于数字的树,可以在此处找到Print BFS (Binary Tree) in Level Order with _specific formatting_,特别是以下示例,取自参考:

def printBfsLevels(graph,start):
queue=[start]
path=[]
currLevel=1
levelMembers=1
height=[(0,start)]
childCount=0
print queue
while queue:
visNode=queue.pop(0)
if visNode not in path:
  if  levelMembers==0:
    levelMembers=childCount
    childCount=0
    currLevel=currLevel+1
  queue=queue+graph.get(visNode,[])
  if levelMembers > 0:
    levelMembers=levelMembers-1
    for node in graph.get(visNode,[]):
      childCount=childCount+1
      height.append((currLevel,node))
  path=path+[visNode]

prevLevel=None

for v,k in sorted(height):
    if prevLevel!=v:
      if prevLevel!=None:
        print "\n"
    prevLevel=v
    print k,
return height

g={1: [2, 3,6], 2: [4, 5], 3: [6, 7],4:[8,9,13]}
printBfsLevels(g,1)

建议将不胜感激。谢谢!

4

1 回答 1

-1

对于图表,我使用 networkx 库。

你应该看看http://networkx.lanl.gov/reference/algorithms.traversal.html

于 2012-06-23T18:24:38.490 回答