Count the nodes of a tree whose weighted string does not contain any duplicate characters | JavaScript implementation of the approach ; Function that returns true if the string contains unique characters ; Function to perform dfs ; If weighted string of the current node contains unique characters ; Weights of the nodes ; Edges of the tree
let cnt = 0 ; let graph = new Array ( ) ; for ( let i = 0 ; i < 100 ; i ++ ) { graph . push ( [ ] ) } let weight = new Array ( 100 ) ; function uniqueChars ( x ) { let mp = new Map ( ) ; let n = x . length ; for ( let i = 0 ; i < n ; i ++ ) { if ( mp . has ( x [ i ] ) ) { mp . set ( x [ i ] , mp . get ( x [ i ] ) + 1 ) } else { mp . set ( x [ i ] , 1 ) } } if ( mp . size == x . length ) return true ; else return false ; } function dfs ( node , parent ) { if ( uniqueChars ( weight [ node ] ) ) cnt += 1 ; for ( let to of graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node ) ; } } weight [ 1 ] = " " ; weight [ 2 ] = " " ; weight [ 3 ] = " " ; weight [ 4 ] = " " ; weight [ 5 ] = " " ; graph [ 1 ] . push ( 2 ) ; graph [ 2 ] . push ( 3 ) ; graph [ 2 ] . push ( 4 ) ; graph [ 1 ] . push ( 5 ) ; dfs ( 1 , 1 ) ; document . write ( cnt ) ;