Skip to content
Guest
Learn DSA · Course Syllabus Show lessons
Searching & Trees · 9 min read · Intermediate

Trees, BFS & DFS Traversal

Traverse hierarchical trees and graphs using Breadth-First Search (Queue) and Depth-First Search (Recursion).

What you'll learn

  • Implement recursive Depth-First Search (DFS) on a binary tree
  • Implement level-by-level Breadth-First Search (BFS) using a Queue
  • Know when BFS beats DFS (shortest path in unweighted graphs)
  • DFS (Depth-First Search): Explores as deep as possible along each branch before backtracking (uses recursion or a Stack). Great for computing tree height, path sums, and topological sort.
  • BFS (Breadth-First Search): Explores level by level (uses a Queue). Guarantees the shortest path (fewest edges) in unweighted graphs.

Fill-in-the-Blank Exercise

Recursive Tree Sum (DFS)

Handle the null base case and recursively sum left and right subtrees.

function treeSum(node) {
if (!node) return ;
return node.val + treeSum(node.left) + treeSum(node.);
}

Live DSA Playground

BFS Level-Order & DFS Tree Sum
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. Which traversal algorithm guarantees finding the shortest path (fewest hops) in an unweighted graph?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind