A tree consisting of n nodes is given, we need to print its DFS.
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
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Clone a Directed Acyclic Graph
- Shortest Path in Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- All Topological Sorts of a Directed Acyclic Graph
- Assign directions to edges so that the directed graph remains acyclic
- Longest path in a directed Acyclic graph | Dynamic Programming
- Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
- Prim’s MST for Adjacency List Representation | Greedy Algo-6
- Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
- Sum of nodes at k-th level in a tree represented as string
- Product of nodes at k-th level in a tree represented as string
- Find Height of Binary Tree represented by Parent array
- Check if a given graph is tree or not
- Difference between graph and tree