VOOZH about

URL: https://www.geeksforgeeks.org/dsa/dfs-n-ary-tree-acyclic-graph-represented-adjacency-list/

⇱ DFS for a n-ary tree (acyclic graph) represented as adjacency list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

DFS for a n-ary tree (acyclic graph) represented as adjacency list

Last Updated : 14 Mar, 2023

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 : 


Output
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)

Comment
Article Tags: