Possible edges of a tree for given diameter , height and vertices | Function to construct the tree ; Special case when d == 2 , only one edge ; Tree is not possible ; Satisfy the height condition by add edges up to h ; Add d - h edges from 1 to satisfy diameter condition ; Remaining edges at vertex 1 or 2 ( d == h ) ; Driver Code
function constructTree ( n , d , h ) { if ( d == 1 ) { if ( n == 2 && h == 1 ) { document . write ( " " , " " ) ; return ; } document . write ( " " , " " ) ; return ; } if ( d > 2 * h ) { document . write ( " " , " " ) ; return ; } for ( var i = 1 ; i <= h ; i ++ ) document . write ( i + " " + ( i + 1 ) , " " ) ; if ( d > h ) { document . write ( " " + " " + ( h + 2 ) , " " ) ; for ( var i = h + 2 ; i <= d ; i ++ ) { document . write ( i + " " + ( i + 1 ) , " " ) ; } } for ( var i = d + 1 ; i < n ; i ++ ) { var k = 1 ; if ( d == h ) k = 2 ; document . write ( k + " " + ( i + 1 ) , " " ) ; } } var n = 5 , d = 3 , h = 2 ; constructTree ( n , d , h ) ;