(DSA – Tree Traversal)
| BFS | DFS |
| (Breadth First Search) | (Depth First Search) |


Difference between BFS and DFS:
| Parameter | BFS | DFS |
| Full Form | Breadth First Search | Depth First Search |
| Definition | BFS (Breadth First Search) is a graph traversal concept where nodes are traversed on same level before moving to next level. | DFS (Depth First Search) is a graph traversal concept where nodes are traversed to depth until a node is reached with no unvisited neighbours. |
| Data Structure | Queue | Stack |
| Concept | Tree builds level by level. | Tree builds sub-tree by sub-tree. |
| Approach | First In First Out (FIFO) | Last In First Out (LIFO) |
| Source | Better when target is closer to given source. | Better when target is farther from given source. |
| Applications | Bipartite Graphs, Shortest Path etc. | Acyclic Graphs, Find Strongly Connected Components etc. |
Program:
Python
#DFS and BFSfrom collections import deque# Define the graphgraph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E']}# BFS - Breadth First Searchdef bfs(graph, start): visited = {start} queue = deque([start]) # FIFO: First In First Out while queue: node = queue.popleft() # return leftmost element print(node, end=' ') for neighbour in graph[node]: if neighbour not in visited: visited.add(neighbour) queue.append(neighbour)# DFS - Depth First Searchdef dfs(graph, start): visited = set() stack = [start] # LIFO: Last In First Out while stack: node = stack.pop() # return rightmost element if node not in visited: print(node, end= ' ') visited.add(node) stack.extend(reversed(graph[node]))print("BFS Traversal:")bfs(graph, 'A') # Output: A B C D E Fprint("\nDFS Traversal:")dfs(graph, 'A') # Output: A B D E F C
Output:

Key Takeaways:
V = number of vertices (nodes)
E = number of edges
Time and Space Complexity:
- BFS: Complete, finds shortest path in unweighted graphs, O(V+E) time, O(V) space due to queue.
- DFS: Not always complete without safeguards, may not find shortest path, O(V+E) time, space O(h) for recursion depth or O(V) for iterative stack.
- BFS is slower and requires more memory space than DFS.
- Choice depends on graph size, depth, and whether shortest path or memory efficiency is the priority.
