Trees
Tree DFS & BFS
Master Depth-First Search (DFS) traversals and Breadth-First Search (BFS) level-order queue architectures.
Last Updated: August 2, 2026
•
15 min read
1. Introduction
What are Tree DFS and BFS?
Why study them?
These two search strategies are the foundations of almost all graph and tree algorithms. Choosing the correct traversal dictates how you solve problems: DFS is ideal for checking paths and heights, whereas BFS is ideal for finding shortest distances or grouping elements level-by-level.Where is it Used?
2. Mental Models
DFS: The Maze Explorer
Imagine exploring a dark maze:BFS: The Water Ripple
Imagine throwing a stone into a still pond:3. Core Algorithms & Implementations
DFS Invariants (Recursive)
BFS Level Order (Iterative)
To group nodes level-by-level, we use a queue. Crucially, before processing a level, we record the size of the queue (levelSize). We only dequeue that many elements, ensuring we don't mix nodes from different levels as children are added.4. Visualizing Traversal Paths
Consider tree [1, 2, 3, 4, 5]:
1 -> 2 -> 4 -> 5 -> 3 (Root -> Left Subtree -> Right Subtree).4 -> 2 -> 5 -> 1 -> 3 (Left Leaf -> Parent -> Right Leaf -> Root).4 -> 5 -> 2 -> 3 -> 1 (Leaves -> Sub-parents -> Root).Level 0: [1], Level 1: [2, 3], Level 2: [4, 5].5. Real-World Examples
6. Interview Perspective
How Interviewers Ask This Topic
Interviewers test structure tracking:#.Common Mistakes
Warning: 1. Forgetting to lock queue size in BFS: Writing
for (int i = 0; i < queue.size(); i++) inside the while loop is bugged. The queue size changes as children are enqueued, mixing nodes from different levels.> 2. Space Complexity of Recursion Stack: Assuming DFS takesO(1)space. For a skewed tree of sizeN, the recursion call stack takesO(N)memory.
7. Summary
levelSize in BFS to process one level at a time.O(N) for both; space is O(H) for DFS stack and O(W) for BFS queue width.8. Quiz
Question 1: What is the maximum width space complexity of BFS?
Answer:O(N) space, which occurs at the bottom level of a perfect binary tree, containing N/2 leaf nodes in the queue.
Question 2: Which traversal prints a Binary Search Tree (BST) in sorted ascending order?
Answer: In-order DFS traversal (Left -> Node -> Right).Question 3: How do you implement DFS iteratively?
Answer: By maintaining an explicit Stack. Push the root. While the stack is not empty, pop a node, process it, and push its right child followed by its left child (left is pushed last so it is popped first).Question 4: True or False: BFS is preferred over DFS for finding the shortest path from the root to a leaf node in an unweighted tree.
Answer: True. Since BFS visits nodes level-by-level, the first leaf node it encounters is guaranteed to be at the shortest depth.Question 5: What is the post-order traversal of a tree with only a root node and a left child?
Answer:[left_child, root]. Post-order processes children before the parent.