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.
- Convert Adjacency Matrix to Adjacency List representation of Graph
- Add and Remove vertex in Adjacency List representation of Graph
- Add and Remove Edge in Adjacency List representation of a Graph
- Clone a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Longest Path in a Directed Acyclic Graph
- Shortest Path in Directed Acyclic Graph
- All Topological Sorts of a Directed Acyclic Graph
- Longest path in a directed Acyclic graph | Dynamic Programming
- Assign directions to edges so that the directed graph remains acyclic
- Count ways to change direction of edges such that graph becomes acyclic
- Add and Remove vertex in Adjacency Matrix representation of Graph
- 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