Created
December 4, 2011 06:05
-
-
Save vishr/1429369 to your computer and use it in GitHub Desktop.
Tree Traversal - Breadth First Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
def iterative_bfs(tree, node, path=[]): | |
""" | |
Iterative breadth first search | |
""" | |
queue = [node] | |
while queue: | |
n = queue.pop(0) | |
path.append(n) | |
queue += tree[n] | |
return path | |
# -------------------- # | |
# 1 # | |
# / | \ # | |
# 2 3 4 # | |
# / \ | \ # | |
# 5 6 7 8 # | |
# / \ | \ # | |
# 9 10 11 12 # | |
# -------------------- # | |
tree = defaultdict(list, { | |
1: [2, 3, 4], | |
2: [5, 6], | |
4: [7, 8], | |
5: [9, 10], | |
7: [11, 12] | |
}) | |
print "iterative_bfs:", iterative_bfs(tree, 1) | |
# iterative_bfs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment