Skip to content

Instantly share code, notes, and snippets.

@ferrata
Last active October 20, 2017 19:23
Show Gist options
  • Save ferrata/774730feec0ec721d56aae7d29466f31 to your computer and use it in GitHub Desktop.
Save ferrata/774730feec0ec721d56aae7d29466f31 to your computer and use it in GitHub Desktop.
bfs
import Queue
class node( object ):
def __init__( self, value, children = None ):
self.value = value
self.children = children or []
def traverse( root ):
# seen = set()
q = Queue.Queue() # stack - Breadth-First
# q = Queue.LifoQueue() # stack - Depth-First
# q = Queue.PriorityQueue() # stack - Dijkstra
q.put( root )
while( not q.empty() ):
node = q.get()
# if node in seen:
# continue
# seen.add( node )
print node.value
# if ...
for child in node.children:
q.put( child )
return None
n = node( 1, [
node( 11, [
node( 111 )
] ),
node( 12, [
node( 121 ),
node( 122 )
] ),
node( 13 ),
] )
traverse( n )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment