![]() |
VOOZH | about |
A tree consisting of n nodes is given, we need to print its DFS.
Examples :
Input : Edges of graph 1 2 1 3 2 4 3 5 Output : 1 2 4 3 5
A simple solution is to do implement standard DFS.
We can modify our approach to avoid extra space for visited nodes. Instead of using the visited array, we can keep track of parent. We traverse all adjacent nodes but the parent.
Below is the implementation :
1 2 4 3 5
Time Complexity: O(V+E) where V is the number of nodes and E is the number of edges in the graph.
Auxiliary space: O(10000)