Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
DFS for a n-ary tree (acyclic graph) represented as adjacency list
Next article icon

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

Last Updated : 14 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 : 

C++
/* CPP code to perform DFS of given tree : */ #include <bits/stdc++.h> using namespace std;  // DFS on tree void dfs(vector<int> list[], int node, int arrival) {     // Printing traversed node     cout << node << '\n';      // Traversing adjacent edges     for (int i = 0; i < list[node].size(); i++) {          // Not traversing the parent node         if (list[node][i] != arrival)             dfs(list, list[node][i], node);     } }  int main() {     // Number of nodes     int nodes = 5;      // Adjacency list     vector<int> list[10000];      // Designing the tree     list[1].push_back(2);     list[2].push_back(1);      list[1].push_back(3);     list[3].push_back(1);      list[2].push_back(4);     list[4].push_back(2);      list[3].push_back(5);     list[5].push_back(3);      // Function call     dfs(list, 1, 0);      return 0; } 
Java
//JAVA Code For DFS for a n-ary tree (acyclic graph) // represented as adjacency list import java.util.*;  class GFG {          // DFS on tree     public static void dfs(LinkedList<Integer> list[],                              int node, int arrival)     {         // Printing traversed node         System.out.println(node);               // Traversing adjacent edges         for (int i = 0; i < list[node].size(); i++) {                   // Not traversing the parent node             if (list[node].get(i) != arrival)                 dfs(list, list[node].get(i), node);         }     }          /* Driver program to test above function */     public static void main(String[] args)      {          // Number of nodes         int nodes = 5;               // Adjacency list         LinkedList<Integer> list[] = new LinkedList[nodes+1];                       for (int i = 0; i < list.length; i ++){             list[i] = new LinkedList<Integer>();         }                  // Designing the tree         list[1].add(2);         list[2].add(1);               list[1].add(3);         list[3].add(1);               list[2].add(4);         list[4].add(2);               list[3].add(5);         list[5].add(3);               // Function call         dfs(list, 1, 0);                       } } // This code is contributed by Arnav Kr. Mandal.   
Python3
# Python3 code to perform DFS of given tree :  # DFS on tree  def dfs(List, node, arrival):          # Printing traversed node      print(node)      # Traversing adjacent edges     for i in range(len(List[node])):          # Not traversing the parent node          if (List[node][i] != arrival):             dfs(List, List[node][i], node)  # Driver Code if __name__ == '__main__':      # Number of nodes      nodes = 5      # Adjacency List      List = [[] for i in range(10000)]      # Designing the tree      List[1].append(2)      List[2].append(1)       List[1].append(3)      List[3].append(1)       List[2].append(4)      List[4].append(2)       List[3].append(5)      List[5].append(3)       # Function call      dfs(List, 1, 0)  # This code is contributed by PranchalK 
C#
// C# Code For DFS for a n-ary tree (acyclic graph)  // represented as adjacency list  using System; using System.Collections.Generic; public class GFG {           // DFS on tree      public static void dfs(List<int> []list,                              int node, int arrival)      {          // Printing traversed node          Console.WriteLine(node);               // Traversing adjacent edges          for (int i = 0; i < list[node].Count; i++) {                   // Not traversing the parent node              if (list[node][i] != arrival)                  dfs(list, list[node][i], node);          }      }           /* Driver program to test above function */     public static void Main(String[] args)      {           // Number of nodes          int nodes = 5;               // Adjacency list          List<int> []list = new List<int>[nodes+1];                       for (int i = 0; i < list.Length; i ++){              list[i] = new List<int>();          }                   // Designing the tree          list[1].Add(2);          list[2].Add(1);               list[1].Add(3);          list[3].Add(1);               list[2].Add(4);          list[4].Add(2);               list[3].Add(5);          list[5].Add(3);               // Function call          dfs(list, 1, 0);                        }  }  // This code contributed by Rajput-Ji 
JavaScript
<script>      // JavaScript Code For DFS for a n-ary tree (acyclic graph)     // represented as adjacency list          // DFS on tree     function dfs(list, node, arrival)     {         // Printing traversed node         document.write(node + "</br>");                 // Traversing adjacent edges         for (let i = 0; i < list[node].length; i++) {                     // Not traversing the parent node             if (list[node][i] != arrival)                 dfs(list, list[node][i], node);         }     }          // Number of nodes     let nodes = 5;      // Adjacency list     let list = new Array(nodes+1);           for (let i = 0; i < list.length; i ++){       list[i] = [];     }      // Designing the tree     list[1].push(2);     list[2].push(1);      list[1].push(3);     list[3].push(1);      list[2].push(4);     list[4].push(2);      list[3].push(5);     list[5].push(3);      // Function call     dfs(list, 1, 0);      </script> 

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)

 


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

R

Rohit Thapliyal
Improve
Article Tags :
  • Tree
  • Graph
  • DSA
  • n-ary-tree
Practice Tags :
  • Graph
  • Tree

Similar Reads

    Print Adjacency List for a Directed Graph
    An Adjacency List is used for representing graphs. Here, for every vertex in the graph, we have a list of all the other vertices which the particular vertex has an edge to. Problem: Given the adjacency list and number of vertices and edges of a graph, the task is to represent the adjacency list for
    6 min read
    Convert Adjacency Matrix to Adjacency List representation of Graph
    Prerequisite: Graph and its representations Given a adjacency matrix representation of a Graph. The task is to convert the given Adjacency Matrix to Adjacency List representation. Examples: Input: arr[][] = [ [0, 0, 1], [0, 0, 1], [1, 1, 0] ] Output: The adjacency list is: 0 -> 2 1 -> 2 2 -
    6 min read
    Add and Remove Edge in Adjacency List representation of a Graph
    Prerequisites: Graph and Its RepresentationIn this article, adding and removing edge is discussed in a given adjacency list representation. A vector has been used to implement the graph using adjacency list representation. It is used to store the adjacency lists of all the vertices. The vertex numbe
    8 min read
    Comparison between Adjacency List and Adjacency Matrix representation of Graph
    A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. In this article, we will understand the difference between the ways of representation of the graph. A gr
    4 min read
    Add and Remove vertex in Adjacency List representation of Graph
    Prerequisites: Linked List, Graph Data StructureIn this article, adding and removing a vertex is discussed in a given adjacency list representation. Let the Directed Graph be: The graph can be represented in the Adjacency List representation as: It is a Linked List representation where the head of t
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences