-1

I'm new to Python, and trying to construct a character-based BFS tree which prints the Parent-child relationships. A closely related solution, but is a number-based tree, is found in this found here Printing BFS (Binary Tree) in Level Order with _specific formatting_ , specifically the following example as taken from the reference:

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)

Suggestions would be greatly appreciated. Thanks!

Community
  • 1
  • 1

1 Answers1

-1

For graphs I use the networkx library.

You should look at http://networkx.lanl.gov/reference/algorithms.traversal.html

Jon Clements
  • 138,671
  • 33
  • 247
  • 280