Skip to content

Instantly share code, notes, and snippets.

@RafaelBroseghini
Last active November 15, 2018 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RafaelBroseghini/4a7a1df783fc0132ea0c4fa59185367e to your computer and use it in GitHub Desktop.
Save RafaelBroseghini/4a7a1df783fc0132ea0c4fa59185367e to your computer and use it in GitHub Desktop.
Breadth First Search
"""
Let's assume we have a Binary Tree.
class BinaryTree(object):
def __init__(self, val):
self.val = val
self.right = None
self.left = None
I understand there may be some breaking of data encapsulation below.
This gist is for demonstration purposes.
"""
def enqueue_valid(node: BinaryTree, queue: list):
for n in [node.left, node.right]:
if n != None:
queue.insert(0, n)
def bfs(root: BinaryTree):
queue = [root]
while len(queue) > 0:
current_node = queue.pop()
print(current_node.val)
enqueue_valid(current_node, queue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment