text: Construct an N | Javascript 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
code: let N = 100000 + 5 ; let visited = new Array ( N ) ; visited . fill ( 0 ) ; function construct_tree ( weights , n ) { let minimum = Number . MAX_VALUE ; let maximum = Number . MIN_VALUE ; for ( let i = 0 ; i < weights . length ; i ++ ) { minimum = Math . min ( minimum , weights [ i ] ) ; maximum = Math . max ( maximum , weights [ i ] ) ; } if ( minimum == maximum ) { document . write ( " " ) ; return ; } else { document . write ( " " + " " ) ; } let root = weights [ 0 ] ; visited [ 1 ] = 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( weights [ i ] != root && visited [ i + 1 ] == 0 ) { document . write ( 1 + " " + ( i + 1 ) + " " ) ; visited [ i + 1 ] = 1 ; } } let notroot = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( weights [ i ] != root ) { notroot = i + 1 ; break ; } } for ( let i = 0 ; i < n ; i ++ ) { if ( weights [ i ] == root && visited [ i + 1 ] == 0 ) { document . write ( notroot + " " + ( i + 1 ) + " " ) ; visited [ i + 1 ] = 1 ; } } } let weights = [ 1 , 2 , 1 , 2 , 5 ] ; let n = weights . length ; construct_tree ( weights , n ) ;