Construct an N | Python3 program to implement the above approach ; Keep track of visited nodes ; Function to construct a tree such that there are no two adjacent nodes with the same weight ; If minimum and maximum elements are equal , i . e . array contains one distinct element ; Tree cannot be constructed ; Otherwise ; Tree can be constructed ; Choose weights [ 0 ] as root ; First Node is visited ; Traverse the array ; Otherwise , make an edge ; Mark this node as visited ; Find a weight not same as the root & make edges with that node ; Join non - roots with remaining nodes ; Check if current node ' s ▁ weight ▁ ▁ is ▁ same ▁ as ▁ root ▁ node ' s weight and if it is not visited or not ; Driver Code ; Function Call
N = 10 ** 5 + 5 NEW_LINE visited = [ 0 ] * N NEW_LINE def construct_tree ( weights , n ) : NEW_LINE INDENT minimum = min ( weights ) NEW_LINE maximum = max ( weights ) NEW_LINE if ( minimum == maximum ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT root = weights [ 0 ] NEW_LINE visited [ 1 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( weights [ i ] != root and visited [ i + 1 ] == 0 ) : NEW_LINE INDENT print ( 1 , i + 1 ) NEW_LINE visited [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT notroot = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( weights [ i ] != root ) : NEW_LINE INDENT notroot = i + 1 NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( weights [ i ] == root and visited [ i + 1 ] == 0 ) : NEW_LINE INDENT print ( notroot , i + 1 ) NEW_LINE visited [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT weights = [ 1 , 2 , 1 , 2 , 5 ] NEW_LINE N = len ( weights ) NEW_LINE construct_tree ( weights , N ) NEW_LINE DEDENT