# DFS for an n-ary Tree(Acyclic Graph) Represented as an Adjacency List

## What is DFS?

Here, the full form of DFS is Depth First Search. With the help of Depth First Search, we can traverse a tree in three ways. These are in order: pre-order and post-order. When a graph contains no cycle of the graph, then this type of graph is known as an acyclic graph. When we connect more than one acyclic graph, then we call it a tree. When there is a possibly disconnected acyclic graph, then it is known as a forest.

Let's begin the article.

## DFS for an n-ary Tree

Before solving the problem, let's know what the n-ary tree is. The other name of the acyclic graph is known as the n-ary tree. But there is one difference between an acyclic graph and an n-ary tree. The difference is when the tree has more than one node, then this is known as an n-ary tree. When there is a need for a non-linear data structure, and we want to create our own data structure, then we have to take the help of an n-ary tree.

The n-ary tree is a subpart of a binary tree, and it has one node on the top as the root node.

The tree has multiple child nodes. It is so hard to traverse all the nodes. Now, we are going to take an example and solve that problem.

Example:

From the below n-ary tree, we have to find out the maximum depth of the tree with the help of Depth First Search.

The pictural representation of the above n-ary tree is as follows:

This is how the graph is traversed; it goes like

A -> B -> D -> E -> H -> I -> J -> K -> C -> F -> G

### Algorithm

We have to solve the above problem by taking the help of the preorder traversal method. In this method, we have to start the traversal from the root node, and then we have to go down to the subtree root node and their children in order. To solve this problem, we have to follow the steps below.

Step-1:

First, we have to start from the root node.

Step-2:

Then, we have to move to the left sub-tree, and that is recursively in nature.

Step-3:

Then, we have to move to the right sub-tree, and that is recursively in nature.

Step-4:

We have to do this process until we do not traverse all the nodes.

If we provide the input as

Then we get the output as below

```A B C D E
```

Let's do the programming part.

### Implementation in C++

Code:

Output:

Explanation:

In the above code, we have implemented the logic in C++ so that it performs the pre-order traversal method and solves the DFS problem.

Code:

Output:

### Explanation:

In the above code, we have implemented the logic in JAVA so that it performs the pre-order traversal method and solves the DFS problem.

Complexity Analysis

Time Complexity

Here, O ( V + E ) is the time complexity of traversing the n-ary tree.

Reason:

In n-ary tree, it takes too much time to traverse the whole tree. That's why the time complexity is this much.

#### Space Complexity

Here, O(V) is the space complexity of traversing the n-ary tree. Here, V represents the Number of vertices.