πΆExplain Like I'm 5
π’ Real-Life Example: Exploring an Office Building
π BFS (Breadth-First Search) = Floor by Floor
You're searching for someone in a building. BFS means you check EVERY room on Floor 1 first, then EVERY room on Floor 2, then Floor 3, and so on.
Uses a Queue (Line): βFirst come, first servedβ - like waiting in line at a store!
Perfect for finding the SHORTEST path or CLOSEST nodes!
ποΈ DFS (Depth-First Search) = One Path All the Way Down
You pick one hallway and explore it COMPLETELY to the end (all rooms, all sub-hallways) before coming back to try another hallway.
Uses a Stack (Pile): βLast in, first outβ - like a stack of plates!
Perfect for exploring ALL possibilities or backtracking problems!
π‘ Key Difference: BFS explores neighbors first (wide), DFS explores children first (deep)!
π Code Debugger
π Queue:
π― Tree Visualization
Click "Start" to begin visualization
π BFS (Java)
Queue-basedpublic List<Integer> BFS(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> result = new ArrayList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
result.add(node.val);
if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}
return result;
}
// Time: O(n), Space: O(w)ποΈ DFS (Java)
Stack-basedpublic List<Integer> DFS(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> result = new ArrayList<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
result.add(node.val);
if (node.right != null)
stack.push(node.right);
if (node.left != null)
stack.push(node.left);
}
return result;
}
// Time: O(n), Space: O(h)