Prufer Code to Tree Creation | C ++ program to construct tree from given Prufer Code ; Prints edges of tree represented by give Prufer code ; Initialize the array of vertices ; Number of occurrences of vertex in code ; Find the smallest label not present in prufer [ ] . ; If j + 1 is not present in prufer set ; Remove from Prufer set and print pair . ; For the last element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printTreeEdges ( int prufer [ ] , int m ) { int vertices = m + 2 ; int vertex_set [ vertices ] ; for ( int i = 0 ; i < vertices ; i ++ ) vertex_set [ i ] = 0 ; for ( int i = 0 ; i < vertices - 2 ; i ++ ) vertex_set [ prufer [ i ] - 1 ] += 1 ; cout << " The edge set E ( G ) is : " int j = 0 ; for ( int i = 0 ; i < vertices - 2 ; i ++ ) { for ( j = 0 ; j < vertices ; j ++ ) { if ( vertex_set [ j ] == 0 ) { vertex_set [ j ] = -1 ; cout << " ( " << ( j + 1 ) << " , ▁ " << prufer [ i ] << " ) ▁ " ; vertex_set [ prufer [ i ] - 1 ] -- ; break ; } } } j = 0 ; 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 ) << " ) STRNEWLINE " ; } } int main ( ) { int prufer [ ] = { 4 , 1 , 3 , 4 } ; int n = sizeof ( prufer ) / sizeof ( prufer [ 0 ] ) ; printTreeEdges ( prufer , n ) ; return 0 ; }