# General - we traverse all nodes at a given depth before moving on to the next depth - implemented iteratively with a [[Queues|Queue]] - you could technically use recursion, but it doesn't make much sense & is a lot more difficult - visits all nodes just like [[DFS]], just in different order - [[DFS]] is more commonly used since it's faster/cleaner to implement - but if you are handling nodes according to their level, BFS is better than DFS - for [[Graphs]] BFS is clearly better when you are asked to find the **shortest path**, most of the time when BFS is better it is this type # For [[Trees]] ``` from collections import deque def print_all_nodes(root): queue = deque([root]) while queue: nodes_in_current_level = len(queue) # do some logic here for the current level for _ in range(nodes_in_current_level): node = queue.popleft() # do some logic here on the current node print(node.val) # put the next level onto the queue if node.left: queue.append(node.left) if node.right: queue.append(node.right) ``` - time complexity is $O(n * k)$, where $n$ is total # of nodes, & $k$ is amount of work done at each node (usually $O(1)$) # For [[Graphs]] -