Breadth first traversal is a method of traversing trees which explores all the nodes at a give level before descending to the next.
The standard implementation uses a queue where elements are pulled from the front of the queue to be processed and then their children are pushed to the end of the queue.
from collections import deque
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def breadth_first_traversal(root, visit):
if root is None:
return
queue = deque([root])
while queue:
current_node = queue.popleft()
visit(current_node.value)
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)