InfoparkDailyCAREER TOOLS

DSA · Lesson 9 of 9

Trees & graphs: BFS and DFS

Traversing trees and graphs, shortest paths in unweighted graphs.

A tree is a hierarchy of nodes with one root and no cycles (folders, org charts, the HTML DOM). A binary search tree keeps smaller values on the left and larger on the right.

A graph is nodes connected by edges — cities and roads, people and connections. Store it as an adjacency list: a dict mapping each node to its neighbours.

  • DFS (depth-first) goes deep before wide — recursion or a stack. Good for exploring all paths, detecting cycles, counting connected parts.
  • BFS (breadth-first) visits level by level with a queue — gives the shortest path in an unweighted graph.

Always track visited nodes in a graph to avoid infinite loops.

Try it yourself

Press Run to see the output.

Edit and press Run (or Ctrl/⌘ + Enter). Python runs in your browser — the first run downloads the Python engine and takes a few seconds.

Key points

  • Adjacency list = dict of neighbours.
  • BFS + queue = shortest path (unweighted).
  • DFS + recursion/stack = explore deeply; track visited.

Quick check

Which traversal finds the shortest path in an unweighted graph?

Practice task

Write count_islands(grid) that counts groups of connected 1s (up/down/left/right) in a 2-D list using DFS.

Interview corner

Why does inorder traversal of a BST give sorted output?

BST rules put smaller keys in the left subtree and larger in the right, so visiting left, node, right outputs keys in ascending order.

BFS vs DFS memory use?

BFS stores a whole frontier level (can be wide); DFS stores the current path (can be deep). Choose based on the graph's shape and what you need.

Further reading

Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.

Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.