# Random Tree Generator Using Prüfer Sequence with Examples

Given an integer N, the task is to generate a random labelled tree of N node with (N – 1) edges without forming cycle.

Note: The output generated below is random which may not match with the output generated by the code.

Examples:

Input: N = 5
Output:
3 2
4 3
1 4
1 5

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

This approach uses the Prüfer Sequence to generate random trees.

What is a Prüfer Sequence?
In combinatorial mathematics, the Prüfer sequence (also Prüfer code or Prüfer numbers) of a labelled tree is a unique sequence associated with the tree. The sequence for a tree on n vertices has length n – 2 and can be generated by a simple iterative algorithm.

If the number of nodes is N then the Prüfer Sequence is of length (N – 2) and each position can have N possible values. So the number of the possible labeled trees with N Nodes is N(N – 2).

How Random Trees are generated using Prüfer Sequence?
Generally, Random Tree Generation with N nodes is done in the following steps:

• Generate a Random Sequence
`S = {s1, s2, s3.....sn-2}`

where each element of the sequence si ∈ {1, 2, 3, … N} where repetition of elements is allowed

• Generate Tree from the generated Prüfer Sequence S:
1. Create N nodes with values {1, 2, 3, … N}
2. Find smallest element X such that X ∈ {1, 2, 3, … N} and X ∉ S
3. Join Node with value X to the node with value s1
4. Delete s1 from S
5. Repeat the same process from step 2 with untill the Prüfer Sequence is empty.

For Example:

Below is the implementation of the above approach.

## C++

 `// C++ Implementation for random ` `// tree generator using Prufer Sequence ` `#include ` `using` `namespace` `std; ` ` `  `// Prints edges of tree ` `// represented by give Prufer code ` `void` `printTreeEdges(``int` `prufer[], ``int` `m) ` `{ ` `    ``int` `vertices = m + 2; ` `    ``int` `vertex_set[vertices]; ` ` `  `    ``// Initialize the array of vertices ` `    ``for` `(``int` `i = 0; i < vertices; i++) ` `        ``vertex_set[i] = 0; ` ` `  `    ``// Number of occurrences of vertex in code ` `    ``for` `(``int` `i = 0; i < vertices - 2; i++) ` `        ``vertex_set[prufer[i] - 1] += 1; ` ` `  `    ``cout<<(``"\nThe edge set E(G) is:\n"``); ` ` `  `    ``int` `j = 0; ` ` `  `    ``// Find the smallest label not present in ` `    ``// prufer[]. ` `    ``for` `(``int` `i = 0; i < vertices - 2; i++)  ` `    ``{ ` `        ``for` `(j = 0; j < vertices; j++) ` `        ``{ ` ` `  `            ``// If j+1 is not present in prufer set ` `            ``if` `(vertex_set[j] == 0) ` `            ``{ ` ` `  `                ``// Remove from Prufer set and print ` `                ``// pair. ` `                ``vertex_set[j] = -1; ` `                ``cout<<``"("` `<< (j + 1) << ``", "` `                                ``<< prufer[i] << ``") "``; ` ` `  `                ``vertex_set[prufer[i] - 1]--; ` ` `  `                ``break``; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``j = 0; ` ` `  `    ``// For the last element ` `    ``for` `(``int` `i = 0; i < vertices; i++) ` `    ``{ ` `        ``if` `(vertex_set[i] == 0 && j == 0) ` `        ``{ ` ` `  `            ``cout << ``"("` `<< (i + 1) << ``", "``; ` `            ``j++; ` `        ``} ` `        ``else` `if` `(vertex_set[i] == 0 && j == 1) ` `            ``cout << (i + 1) << ``")\n"``; ` `    ``} ` `} ` ` `  `// generate random numbers in between l an r ` `int` `ran(``int` `l, ``int` `r) ` `{ ` `    ``return` `l + (``rand``() % (r - l + 1)); ` `} ` ` `  `// Function to Generate Random Tree ` `void` `generateRandomTree(``int` `n) ` `{ ` ` `  `    ``int` `length = n - 2; ` `    ``int` `arr[length]; ` ` `  `    ``// Loop to Generate Random Array ` `    ``for` `(``int` `i = 0; i < length; i++)  ` `    ``{ ` `        ``arr[i] = ran(0, ``pow``(2, length + 1)) + 1; ` `    ``} ` `    ``printTreeEdges(arr, length); ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``srand``(``time``(0)); ` `    ``int` `n = 5; ` `    ``generateRandomTree(n); ` ` `  `    ``return` `0; ` `} ` ` `  `// This code is contributed by Arnab Kundu `

## Java

 `// Java Implementation for random ` `// tree generator using Prufer Sequence ` ` `  `import` `java.util.Arrays; ` `import` `java.util.Random; ` ` `  `class` `GFG { ` ` `  `    ``// Prints edges of tree ` `    ``// represented by give Prufer code ` `    ``static` `void` `printTreeEdges(``int` `prufer[], ``int` `m) ` `    ``{ ` `        ``int` `vertices = m + ``2``; ` `        ``int` `vertex_set[] = ``new` `int``[vertices]; ` ` `  `        ``// Initialize the array of vertices ` `        ``for` `(``int` `i = ``0``; i < vertices; i++) ` `            ``vertex_set[i] = ``0``; ` ` `  `        ``// Number of occurrences of vertex in code ` `        ``for` `(``int` `i = ``0``; i < vertices - ``2``; i++) ` `            ``vertex_set[prufer[i] - ``1``] += ``1``; ` ` `  `        ``System.out.print(``"\nThe edge set E(G) is:\n"``); ` ` `  `        ``int` `j = ``0``; ` ` `  `        ``// Find the smallest label not present in ` `        ``// prufer[]. ` `        ``for` `(``int` `i = ``0``; i < vertices - ``2``; i++) { ` `            ``for` `(j = ``0``; j < vertices; j++) { ` ` `  `                ``// If j+1 is not present in prufer set ` `                ``if` `(vertex_set[j] == ``0``) { ` ` `  `                    ``// Remove from Prufer set and print ` `                    ``// pair. ` `                    ``vertex_set[j] = -``1``; ` `                    ``System.out.print(``"("` `+ (j + ``1``) + ``", "` `                                     ``+ prufer[i] + ``") "``); ` ` `  `                    ``vertex_set[prufer[i] - ``1``]--; ` ` `  `                    ``break``; ` `                ``} ` `            ``} ` `        ``} ` ` `  `        ``j = ``0``; ` ` `  `        ``// For the last element ` `        ``for` `(``int` `i = ``0``; i < vertices; i++) { ` `            ``if` `(vertex_set[i] == ``0` `&& j == ``0``) { ` ` `  `                ``System.out.print(``"("` `+ (i + ``1``) + ``", "``); ` `                ``j++; ` `            ``} ` `            ``else` `if` `(vertex_set[i] == ``0` `&& j == ``1``) ` `                ``System.out.print((i + ``1``) + ``")\n"``); ` `        ``} ` `    ``} ` ` `  `    ``// Function to Generate Random Tree ` `    ``static` `void` `generateRandomTree(``int` `n) ` `    ``{ ` ` `  `        ``Random rand = ``new` `Random(); ` `        ``int` `length = n - ``2``; ` `        ``int``[] arr = ``new` `int``[length]; ` ` `  `        ``// Loop to Generate Random Array ` `        ``for` `(``int` `i = ``0``; i < length; i++) { ` `            ``arr[i] = rand.nextInt(length + ``1``) + ``1``; ` `        ``} ` `        ``printTreeEdges(arr, length); ` `    ``} ` ` `  `    ``// Driver Code ` `    ``public` `static` `void` `main(String[] args) ` `    ``{ ` `        ``int` `n = ``5``; ` `        ``generateRandomTree(n); ` `    ``} ` `} `

## C#

 `// C# Implementation for random ` `// tree generator using Prufer Sequence ` `using` `System; ` ` `  `class` `GFG ` `{ ` ` `  `    ``// Prints edges of tree ` `    ``// represented by give Prufer code ` `    ``static` `void` `printTreeEdges(``int` `[]prufer, ``int` `m) ` `    ``{ ` `        ``int` `vertices = m + 2; ` `        ``int` `[]vertex_set = ``new` `int``[vertices]; ` ` `  `        ``// Initialize the array of vertices ` `        ``for` `(``int` `i = 0; i < vertices; i++) ` `            ``vertex_set[i] = 0; ` ` `  `        ``// Number of occurrences of vertex in code ` `        ``for` `(``int` `i = 0; i < vertices - 2; i++) ` `            ``vertex_set[prufer[i] - 1] += 1; ` ` `  `        ``Console.Write(``"\nThe edge set E(G) is:\n"``); ` ` `  `        ``int` `j = 0; ` ` `  `        ``// Find the smallest label not present in ` `        ``// prufer[]. ` `        ``for` `(``int` `i = 0; i < vertices - 2; i++)  ` `        ``{ ` `            ``for` `(j = 0; j < vertices; j++) ` `            ``{ ` ` `  `                ``// If j + 1 is not present in prufer set ` `                ``if` `(vertex_set[j] == 0) ` `                ``{ ` ` `  `                    ``// Remove from Prufer set and print ` `                    ``// pair. ` `                    ``vertex_set[j] = -1; ` `                    ``Console.Write(``"("` `+ (j + 1) + ``", "` `                                    ``+ prufer[i] + ``") "``); ` ` `  `                    ``vertex_set[prufer[i] - 1]--; ` ` `  `                    ``break``; ` `                ``} ` `            ``} ` `        ``} ` ` `  `        ``j = 0; ` ` `  `        ``// For the last element ` `        ``for` `(``int` `i = 0; i < vertices; i++) ` `        ``{ ` `            ``if` `(vertex_set[i] == 0 && j == 0)  ` `            ``{ ` ` `  `                ``Console.Write(``"("` `+ (i + 1) + ``", "``); ` `                ``j++; ` `            ``} ` `            ``else` `if` `(vertex_set[i] == 0 && j == 1) ` `                ``Console.Write((i + 1) + ``")\n"``); ` `        ``} ` `    ``} ` ` `  `    ``// Function to Generate Random Tree ` `    ``static` `void` `generateRandomTree(``int` `n) ` `    ``{ ` ` `  `        ``Random rand = ``new` `Random(); ` `        ``int` `length = n - 2; ` `        ``int``[] arr = ``new` `int``[length]; ` ` `  `        ``// Loop to Generate Random Array ` `        ``for` `(``int` `i = 0; i < length; i++)  ` `        ``{ ` `            ``arr[i] = rand.Next(length + 1) + 1; ` `        ``} ` `        ``printTreeEdges(arr, length); ` `    ``} ` ` `  `    ``// Driver Code ` `    ``public` `static` `void` `Main(String[] args) ` `    ``{ ` `        ``int` `n = 5; ` `        ``generateRandomTree(n); ` `    ``} ` `} ` ` `  `// This code is contributed by 29AjayKumar `

Output:

```The edge set E(G) is:
(2, 4) (4, 3) (3, 1) (1, 5)
```

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.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

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.

Improved By : 29AjayKumar, andrew1234

Article Tags :
Practice Tags :

1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.