Count nodes having Bitwise XOR of all edges in their path from the root equal to K | Initialize the adjacency list to represent the tree ; Marks visited / unvisited vertices ; Stores the required count of nodes ; DFS to visit each vertex ; Mark the current node as visited ; Update the counter xor is K ; Visit adjacent nodes ; Calculate Bitwise XOR of edges in the path ; Recursive call to dfs function ; Function to construct the tree and print required count of nodes ; Add edges ; Print answer ; Given K and R ; Given edges ; Number of vertices ; Function call
let adj = [ ] ; for ( let i = 0 ; i < 100005 ; i ++ ) { adj . push ( [ ] ) } let visited = new Array ( 100005 ) . fill ( 0 ) ; let ans = 0 ; function dfs ( node , xorr , k ) { visited [ node ] = 1 ; if ( node != 1 && xorr == k ) ans ++ ; for ( let x of adj [ node ] ) { if ( ! visited [ x [ 0 ] ] ) { let xorr1 = xorr ^ x [ 1 ] ; dfs ( x [ 0 ] , xorr1 , k ) ; } } } function countNodes ( N , K , R , edges ) { for ( let i = 0 ; i < N - 1 ; i ++ ) { let u = edges [ i ] [ 0 ] , v = edges [ i ] [ 1 ] , w = edges [ i ] [ 2 ] ; adj [ u ] . push ( [ v , w ] ) ; adj [ v ] . push ( [ u , w ] ) ; } dfs ( R , 0 , K ) ; document . write ( ans + " " ) ; } let K = 0 , R = 1 ; let edges = [ [ 1 , 2 , 3 ] , [ 1 , 3 , 1 ] , [ 2 , 4 , 3 ] , [ 2 , 5 , 4 ] , [ 3 , 6 , 1 ] , [ 3 , 7 , 2 ] ] ; let N = edges . length ; countNodes ( N , K , R , edges ) ;