What is depth-first tree traversal (DFS)?
Depth-first traversal (DFS, Depth-First Search) is a way of traversing a tree in which the algorithm goes deep along a branch until it reaches the end (a leaf), and only then backtracks to walk the other branches.
Principle
- Start at the root.
- Follow the first available child all the way down.
- When you can't go any further, backtrack to the previous node.
- Continue until every node has been visited.
- It is usually implemented with a stack (LIFO), either explicitly or via recursion.
Example
javascript
A
/ \
B C
/ \
D EPossible traversal types (DFS variants):
- Pre-order: A, B, D, E, C
- In-order: D, B, E, A, C
- Post-order: D, E, B, C, A
Features of DFS
- Uses a stack or recursion.
- Good for tasks where you need to explore the whole structure or find a path down to depth.
- Can be faster than BFS if the target element is deep in the tree.
Summary
DFS is a traversal that goes deep along branches, exploring each branch fully before moving on to the next one. It is implemented with a stack or recursion and has three main traversal orders: pre-, in-, post-order.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.