Skip to main content

Breadth-First Search (BFS)

The breadth-first search algorithm is used to traverse or search tree/graph data structures by exploring all nodes at the present depth before moving on to nodes at the next depth level.

Time Complexity: O(n)O(n)

Space Complexity: O(w)O(w), where w is the maximum width of the tree

Implementation

from collections import deque

class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

def bfs(root):
if not root:
return
queue = deque([root])
while queue:
node = queue.popleft()
# Process current node
print(node.val)
# Add children to queue
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)