Minimum steps to color the tree with given colors | Java implementation of the approach ; 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
import java . util . * ; class GFG { static int ans = 0 ; static Vector < Vector < Integer > > gr = new Vector < Vector < Integer > > ( ) ; static void Add_Edge ( int u , int v ) { gr . get ( u ) . add ( v ) ; gr . get ( v ) . add ( u ) ; } static void dfs ( int child , int par , int color [ ] ) { if ( color [ child ] != color [ par ] ) ans ++ ; for ( int i = 0 ; i < gr . get ( child ) . size ( ) ; i ++ ) { if ( gr . get ( child ) . get ( i ) == par ) continue ; dfs ( gr . get ( child ) . get ( i ) , child , color ) ; } } public static void main ( String args [ ] ) { for ( int i = 0 ; i <= 10 ; i ++ ) gr . add ( new Vector < Integer > ( ) ) ; int 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 ) ; System . out . println ( ans ) ; } }