Minimum steps to color the tree with given colors | To store the required answer ; To store the graph ; Function to add edges ; Dfs function ; When there is difference in colors ; For all it 's child nodes ; Driver code ; Here zero is for parent of node 1 ; Adding edges in the graph ; Dfs call ; Required answer
let ans = 0 ; let gr = [ ] ; function Add_Edge ( u , v ) { gr [ u ] . push ( v ) ; gr [ v ] . push ( u ) ; } function dfs ( child , par , color ) { if ( color [ child ] != color [ par ] ) ans ++ ; for ( let i = 0 ; i < gr [ child ] . length ; i ++ ) { if ( gr [ child ] [ i ] == par ) continue ; dfs ( gr [ child ] [ i ] , child , color ) ; } } for ( let i = 0 ; i <= 10 ; i ++ ) gr . push ( [ ] ) ; let color = [ 0 , 1 , 2 , 3 , 2 , 2 , 3 ] ; Add_Edge ( 1 , 2 ) ; Add_Edge ( 1 , 3 ) ; Add_Edge ( 2 , 4 ) ; Add_Edge ( 2 , 5 ) ; Add_Edge ( 3 , 6 ) ; dfs ( 1 , 0 , color ) ; document . write ( ans ) ;