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 email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Convert Adjacency Matrix to Adjacency List representation of Graph
- Comparison between Adjacency List and Adjacency Matrix representation of Graph
- Add and Remove Edge in Adjacency List representation of a Graph
- Add and Remove vertex in Adjacency List representation of Graph
- Clone a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- All Topological Sorts of a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph
- Shortest Path in Directed Acyclic Graph
- Assign directions to edges so that the directed graph remains acyclic
- Longest path in a directed Acyclic graph | Dynamic Programming
- Count ways to change direction of edges such that graph becomes acyclic
- C program to implement Adjacency Matrix of a given Graph
- Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
- Add and Remove vertex in Adjacency Matrix representation of Graph
- 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
- Check if all nodes of the Binary Tree can be represented as sum of two primes
- Product of nodes at k-th level in a tree represented as string