# Convert Directed Graph into a Tree

Given an array **arr[]** of size **N**. There is an edge from **i** to **arr[i]**. The task is to convert this directed graph into tree by changing some of the edges. If for some **i**, **arr[i] = i** then **i** represents the root of the tree. In case of multiple answers print any of them.

**Examples:**

Input:arr[] = {6, 6, 0, 1, 4, 3, 3, 4, 0}

Output:{6, 6, 0, 1, 4, 3, 4, 4, 0}

Input:arr[] = {1, 2, 0};

Output:{0, 2, 0}.

**Approach:** Consider the 2nd example image above which shows an example of a functional graph. It consists of two cycles 1, 6, 3 and 4. Our goal is to make the graph consisting of exactly one cycle of exactly one vertex looped to itself.

Operation of change is equivalent to removing some outgoing edge and adding a new one, going to somewhat else vertex. Let’s firstly make our graph containing only one cycle. To do so, one can choose any of initially presented cycles and say that it will be the only one. Then one should consider every other cycle, remove any of its in-cycle edges and replace it with an edge going to any of the chosen cycle’s vertices. Thus the cycle will be broken and its vertices (along with tree ones) will be connected to the only chosen cycle. One will need to do exactly **cycleCount – 1** such operations. Note that the removing of any non-cycle edge does not make sense, because it does not break any cycle.

The next thing is to make the cycle length be equal to 1. That might be already satisfied, if one will choose a cycle of minimal length and this length equals 1. Thus, if the initial graph contains any cycle of length 1, we are done with **cycleCount – 1** operations. Otherwise, the cycle contains more than one vertex. It can be fixed with exactly one operation – one just needs to break any of in-cycle edges, say from u to arr[u], and add an edge from u to u. The graph will remain consisting of one cycle, but consisting of one self-looped vertex. In that case, we are done with cycleCount operations.

To do all the operations above, one can use DSU structure, or just a series of DFS. Note that there is no need in realisation of edge removing and creating, one just needs to analyze initial graph.

Below is the implementation of the above approach:

## C++

`// CPP program to convert directed graph into tree ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Function to find root of the vertex ` `int` `find(` `int` `x, ` `int` `a[], ` `int` `vis[], ` `int` `root[]) ` `{ ` ` ` `if` `(vis[x]) ` ` ` `return` `root[x]; ` ` ` ` ` `vis[x] = 1; ` ` ` `root[x] = x; ` ` ` `root[x] = find(a[x], a, vis, root); ` ` ` `return` `root[x]; ` `} ` ` ` `// Function to convert directed graph into tree ` `void` `Graph_to_tree(` `int` `a[], ` `int` `n) ` `{ ` ` ` `// Vis array to check if an index is visited or not ` ` ` `// root[] array is to store parent of each vertex ` ` ` `int` `vis[n] = { 0 }, root[n] = { 0 }; ` ` ` ` ` `// Find parent of each parent ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `find(a[i], a, vis, root); ` ` ` ` ` `// par stores the root of the resulting tree ` ` ` `int` `par = -1; ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `if` `(i == a[i]) ` ` ` `par = i; ` ` ` ` ` `// If no self loop exists ` ` ` `if` `(par == -1) { ` ` ` `for` `(` `int` `i = 0; i < n; i++) { ` ` ` ` ` `// Make vertex in a cycle as root of the tree ` ` ` `if` `(i == find(a[i], a, vis, root)) { ` ` ` `par = i; ` ` ` `a[i] = i; ` ` ` `break` `; ` ` ` `} ` ` ` `} ` ` ` `} ` ` ` ` ` `// Remove all cycles ` ` ` `for` `(` `int` `i = 0; i < n; i++) { ` ` ` `if` `(i == find(a[i], a, vis, root)) { ` ` ` `a[i] = par; ` ` ` `} ` ` ` `} ` ` ` ` ` `// Print the resulting array ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `cout << a[i] << ` `" "` `; ` `} ` ` ` `// Driver code to test above functions ` `int` `main() ` `{ ` ` ` `int` `a[] = { 6, 6, 0, 1, 4, 3, 3, 4, 0 }; ` ` ` ` ` `int` `n = ` `sizeof` `(a) / ` `sizeof` `(a[0]); ` ` ` ` ` `// Function call ` ` ` `Graph_to_tree(a, n); ` `} ` |

*chevron_right*

*filter_none*

## Java

`// Java program to convert ` `// directed graph into tree ` `import` `java.util.*; ` ` ` `class` `GFG ` `{ ` ` ` `// Function to find root of the vertex ` `static` `int` `find(` `int` `x, ` `int` `a[], ` ` ` `int` `vis[], ` `int` `root[]) ` `{ ` ` ` `if` `(vis[x] == ` `1` `) ` ` ` `return` `root[x]; ` ` ` ` ` `vis[x] = ` `1` `; ` ` ` `root[x] = x; ` ` ` `root[x] = find(a[x], a, vis, root); ` ` ` `return` `root[x]; ` `} ` ` ` `// Function to convert directed graph into tree ` `static` `void` `Graph_to_tree(` `int` `a[], ` `int` `n) ` `{ ` ` ` `// Vis array to check if an index is ` ` ` `// visited or not root[] array is to ` ` ` `// store parent of each vertex ` ` ` `int` `[]vis = ` `new` `int` `[n]; ` ` ` `int` `[]root = ` `new` `int` `[n]; ` ` ` ` ` `// Find parent of each parent ` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++) ` ` ` `find(a[i], a, vis, root); ` ` ` ` ` `// par stores the root of the resulting tree ` ` ` `int` `par = -` `1` `; ` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++) ` ` ` `if` `(i == a[i]) ` ` ` `par = i; ` ` ` ` ` `// If no self loop exists ` ` ` `if` `(par == -` `1` `) ` ` ` `{ ` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++) ` ` ` `{ ` ` ` ` ` `// Make vertex in a cycle as root of the tree ` ` ` `if` `(i == find(a[i], a, vis, root)) ` ` ` `{ ` ` ` `par = i; ` ` ` `a[i] = i; ` ` ` `break` `; ` ` ` `} ` ` ` `} ` ` ` `} ` ` ` ` ` `// Remove all cycles ` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++) ` ` ` `{ ` ` ` `if` `(i == find(a[i], a, vis, root)) ` ` ` `{ ` ` ` `a[i] = par; ` ` ` `} ` ` ` `} ` ` ` ` ` `// Print the resulting array ` ` ` `for` `(` `int` `i = ` `0` `; i < n; i++) ` ` ` `System.out.print(a[i] + ` `" "` `); ` `} ` ` ` `// Driver Code ` `static` `public` `void` `main ( String []arr) ` `{ ` ` ` `int` `a[] = { ` `6` `, ` `6` `, ` `0` `, ` `1` `, ` `4` `, ` `3` `, ` `3` `, ` `4` `, ` `0` `}; ` ` ` ` ` `int` `n = a.length; ` ` ` ` ` `// Function call ` ` ` `Graph_to_tree(a, n); ` `} ` `} ` ` ` `// This code is contributed by 29AjayKumar ` |

*chevron_right*

*filter_none*

## Python3

`# A Python3 program to convert ` `# directed graph into tree ` ` ` `# Function to find root of the vertex ` `def` `find(x, a, vis, root): ` ` ` `if` `vis[x]: ` ` ` `return` `root[x] ` ` ` ` ` `vis[x] ` `=` `1` ` ` `root[x] ` `=` `x ` ` ` `root[x] ` `=` `find(a[x], a, vis, root) ` ` ` `return` `root[x] ` ` ` `# Function to convert directed graph into tree ` `def` `Graph_To_Tree(a, n): ` ` ` ` ` `# Vis array to check if an index is visited or not ` ` ` `# root[] array is to store parent of each vertex ` ` ` `vis ` `=` `[` `0` `] ` `*` `n ` ` ` `root ` `=` `[` `0` `] ` `*` `n ` ` ` ` ` `# Find parent of each parent ` ` ` `for` `i ` `in` `range` `(n): ` ` ` `find(a[i], a, vis, root) ` ` ` ` ` `# par stores the root of the resulting tree ` ` ` `par ` `=` `-` `1` ` ` `for` `i ` `in` `range` `(n): ` ` ` `if` `i ` `=` `=` `a[i]: ` ` ` `par ` `=` `i ` ` ` ` ` `# If no self loop exists ` ` ` `if` `par ` `=` `=` `-` `1` `: ` ` ` `for` `i ` `in` `range` `(n): ` ` ` ` ` `# Make vertex in a cycle as root of the tree ` ` ` `if` `i ` `=` `=` `find(a[i], a, vis, root): ` ` ` `par ` `=` `i ` ` ` `a[i] ` `=` `i ` ` ` `break` ` ` ` ` `# Remove all cycles ` ` ` `for` `i ` `in` `range` `(n): ` ` ` `if` `i ` `=` `=` `find(a[i], a, vis, root): ` ` ` `a[i] ` `=` `par ` ` ` ` ` `# Print the resulting array ` ` ` `for` `i ` `in` `range` `(n): ` ` ` `print` `(a[i], end ` `=` `" "` `) ` ` ` `# Driver Code ` `if` `__name__ ` `=` `=` `"__main__"` `: ` ` ` `a ` `=` `[` `6` `, ` `6` `, ` `0` `, ` `1` `, ` `4` `, ` `3` `, ` `3` `, ` `4` `, ` `0` `] ` ` ` `n ` `=` `len` `(a) ` ` ` ` ` `# Function call ` ` ` `Graph_To_Tree(a, n) ` ` ` `# This code is contributed by ` `# sanjeev2552 ` |

*chevron_right*

*filter_none*

## C#

`// C# program to convert ` `// directed graph into tree ` `using` `System; ` `using` `System.Collections.Generic; ` ` ` `class` `GFG ` `{ ` ` ` `// Function to find root of the vertex ` `static` `int` `find(` `int` `x, ` `int` `[]a, ` ` ` `int` `[]vis, ` `int` `[]root) ` `{ ` ` ` `if` `(vis[x] == 1) ` ` ` `return` `root[x]; ` ` ` ` ` `vis[x] = 1; ` ` ` `root[x] = x; ` ` ` `root[x] = find(a[x], a, vis, root); ` ` ` `return` `root[x]; ` `} ` ` ` `// Function to convert directed graph into tree ` `static` `void` `Graph_to_tree(` `int` `[]a, ` `int` `n) ` `{ ` ` ` `// Vis array to check if an index is ` ` ` `// visited or not root[] array is to ` ` ` `// store parent of each vertex ` ` ` `int` `[]vis = ` `new` `int` `[n]; ` ` ` `int` `[]root = ` `new` `int` `[n]; ` ` ` ` ` `// Find parent of each parent ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `find(a[i], a, vis, root); ` ` ` ` ` `// par stores the root of the resulting tree ` ` ` `int` `par = -1; ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `if` `(i == a[i]) ` ` ` `par = i; ` ` ` ` ` `// If no self loop exists ` ` ` `if` `(par == -1) ` ` ` `{ ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `{ ` ` ` ` ` `// Make vertex in a cycle as root of the tree ` ` ` `if` `(i == find(a[i], a, vis, root)) ` ` ` `{ ` ` ` `par = i; ` ` ` `a[i] = i; ` ` ` `break` `; ` ` ` `} ` ` ` `} ` ` ` `} ` ` ` ` ` `// Remove all cycles ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `{ ` ` ` `if` `(i == find(a[i], a, vis, root)) ` ` ` `{ ` ` ` `a[i] = par; ` ` ` `} ` ` ` `} ` ` ` ` ` `// Print the resulting array ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `Console.Write(a[i] + ` `" "` `); ` `} ` ` ` `// Driver Code ` `static` `public` `void` `Main ( String []arr) ` `{ ` ` ` `int` `[]a = { 6, 6, 0, 1, 4, 3, 3, 4, 0 }; ` ` ` ` ` `int` `n = a.Length; ` ` ` ` ` `// Function call ` ` ` `Graph_to_tree(a, n); ` `} ` `} ` ` ` `// This code is contributed by Princi Singh ` |

*chevron_right*

*filter_none*

**Output:**

6 6 0 1 4 3 4 4 0

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.

## Recommended Posts:

- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Convert undirected connected graph to strongly connected directed graph
- Detect Cycle in a Directed Graph
- Check if a directed graph is connected or not
- Clone a Directed Acyclic Graph
- Detect Cycle in a Directed Graph using BFS
- Hierholzer's Algorithm for directed graph
- Euler Circuit in a Directed Graph
- Find dependencies of each Vertex in a Directed Graph
- Path with minimum XOR sum of edges in a directed graph
- Find if there is a path between two vertices in a directed graph
- Detect Cycle in a directed graph using colors
- All Topological Sorts of a Directed Acyclic Graph
- Shortest Path in Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Longest Path in a Directed Acyclic Graph
- Number of shortest paths in an unweighted and directed graph
- Find the number of paths of length K in a directed graph
- Determine whether a universal sink exists in a directed graph
- Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.