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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Convert Adjacency Matrix to Adjacency List representation of Graph
- Comparison between Adjacency List and Adjacency Matrix representation of Graph
- Convert Adjacency List to Adjacency Matrix representation of a Graph
- Calculate number of nodes between two vertices in an acyclic Graph by DFS method
- Add and Remove vertex in Adjacency List representation of Graph
- Add and Remove Edge in Adjacency List representation of a Graph
- Shortest Path in Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph
- Assign directions to edges so that the directed graph remains acyclic
- All Topological Sorts of a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Clone a Directed Acyclic Graph
- Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
- Minimum number of edges required to be removed from an Undirected Graph to make it acyclic
- Count permutations of all integers upto N that can form an acyclic graph based on given conditions
- Longest path in a directed Acyclic graph | Dynamic Programming
- Minimum time taken by each job to be completed given by a Directed Acyclic Graph
- Count ways to change direction of edges such that graph becomes acyclic
- Add and Remove vertex in Adjacency Matrix representation of Graph
- C program to implement Adjacency Matrix of a given Graph