Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path | Function to assign values to nodes of the tree s . t . sum of values of nodes of path between any 2 nodes is not divisible by length of path ; Stores the adjacency list ; Create a adjacency list ; Stores whether node is visited or not ; Stores the node values ; Variable used to assign values to the nodes alternatively to the parent child ; Declare a queue ; Push the 1 st node ; Assign K value to this node ; Dequeue the node ; Mark it as visited ; Upgrade the value of K ; Assign K to the child nodes ; If the child is unvisited ; Enqueue the child ; Assign K to the child ; Print the value assigned to the nodes ; Driver Code ; Function Call
function assignValues ( Edges , n ) { var tree = Array . from ( Array ( n + 1 ) , ( ) => Array ( ) ) ; for ( var i = 0 ; i < n - 1 ; i ++ ) { var u = Edges [ i ] [ 0 ] ; var v = Edges [ i ] [ 1 ] ; tree [ u ] . push ( v ) ; tree [ v ] . push ( u ) ; } var visited = Array ( n + 1 ) . fill ( false ) ; var answer = Array ( n + 1 ) ; var K = 1 ; var q = [ ] ; q . push ( 1 ) ; answer [ 1 ] = K ; while ( q . length != 0 ) { var node = q [ 0 ] ; q . shift ( ) ; visited [ node ] = true ; K = ( ( answer [ node ] == 1 ) ? 2 : 1 ) ; tree [ node ] . forEach ( child => { if ( ! visited [ child ] ) { q . push ( child ) ; answer [ child ] = K ; } } ) ; } for ( var i = 1 ; i <= n ; i ++ ) { document . write ( answer [ i ] + " " ) ; } } var N = 11 ; var Edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 2 , 6 ] , [ 2 , 10 ] , [ 10 , 11 ] , [ 3 , 7 ] , [ 4 , 8 ] , [ 5 , 9 ] ] ; assignValues ( Edges , N ) ;