Overview
Explores one path fully in a graph or tree before returning to try other paths.| Time | Space |
|---|---|
O(n) | O(h) |
Tree DFS
Example Tree:

Order of Searching
-
Pre-order:
Node -> Left -> Right.- [60, 59, 28, 23, 28, 35, 77, 60, 76, 125]
-
In-order:
Left -> Node -> Right.- [23, 28, 28, 35, 59, 60, 60, 76, 77, 125]
-
Post-order:
Left -> Right -> Node.- [23, 35, 28, 28, 59, 76, 60, 125, 77, 60]
The order of visiting children can be changed, such as visiting the right child before the left. To do this, simply swap the code for the left and right child traversals (use right before left) in the implementation below.
Implementation
Go to Binary Search Tree for the complete BST implementation.
Binary Search Tree
Pre-order
In-order
Post-order
Graph DFS
Example Graph:

Adjacency Matrix
Graph DFS (adjacency matrix)
Adjacency List
Graph DFS (adjacency list)
Matrix (2D Array) DFS
Example 2D Array:
The red line shows the search flow starting from points

row: 0 and col: 0.Implementation
Matrix DFS