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
def constructTree ( n , d , h ) : NEW_LINE INDENT if d == 1 : NEW_LINE INDENT if n == 2 and h == 1 : NEW_LINE INDENT print ( "1 ▁ 2" ) NEW_LINE return 0 NEW_LINE DEDENT print ( " - 1" ) NEW_LINE return 0 NEW_LINE DEDENT if d > 2 * h : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return 0 NEW_LINE DEDENT for i in range ( 1 , h + 1 ) : NEW_LINE INDENT print ( i , " ▁ " , i + 1 ) NEW_LINE DEDENT if d > h : NEW_LINE INDENT print ( 1 , " ▁ " , h + 2 ) NEW_LINE for i in range ( h + 2 , d + 1 ) : NEW_LINE INDENT print ( i , " ▁ " , i + 1 ) NEW_LINE DEDENT DEDENT for i in range ( d + 1 , n ) : NEW_LINE INDENT k = 1 NEW_LINE if d == h : NEW_LINE INDENT k = 2 NEW_LINE DEDENT print ( k , " ▁ " , i + 1 ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE d = 3 NEW_LINE h = 2 NEW_LINE constructTree ( n , d , h ) NEW_LINE