DP on Trees | Set | C # program to find diameter of a tree using DFS . ; Function to find the diameter of the tree using Dynamic Programming ; Store the first maximum and secondmax ; Traverse for all children of node ; Call DFS function again ; Find first max ; Secondmaximum ; Find secondmaximum ; Base case for every node ; if ( firstmax != - 1 ) Add ; Find dp [ 2 ] ; Return maximum of both ; Constructed tree is 1 / \ 2 3 / \ 4 5 ; create undirected edges ; Find diameter by calling function
using System ; using System . Collections . Generic ; class GFG { static int dfs ( int node , int parent , int [ ] dp1 , int [ ] dp2 , List < List < int > > adj ) { int firstmax = - 1 ; int secondmax = - 1 ; for ( int i = 0 ; i < adj [ node ] . Count ; ++ i ) { if ( adj [ node ] [ i ] == parent ) continue ; dfs ( adj [ node ] [ i ] , node , dp1 , dp2 , adj ) ; if ( firstmax == - 1 ) { firstmax = dp1 [ adj [ node ] [ i ] ] ; } else if ( dp1 [ adj [ node ] [ i ] ] >= firstmax ) { secondmax = firstmax ; firstmax = dp1 [ adj [ node ] [ i ] ] ; } else if ( dp1 [ adj [ node ] [ i ] ] > secondmax ) { secondmax = dp1 [ adj [ node ] [ i ] ] ; } } dp1 [ node ] = 1 ; dp1 [ node ] += firstmax ; if ( secondmax != - 1 ) dp2 [ node ] = 1 + firstmax + secondmax ; return Math . Max ( dp1 [ node ] , dp2 [ node ] ) ; } static void Main ( ) { int n = 5 ; List < List < int > > adj = new List < List < int > > ( ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) { adj . Add ( new List < int > ( ) ) ; } adj [ 1 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 1 ) ; adj [ 1 ] . Add ( 3 ) ; adj [ 3 ] . Add ( 1 ) ; adj [ 2 ] . Add ( 4 ) ; adj [ 4 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 5 ) ; adj [ 5 ] . Add ( 2 ) ; int [ ] dp1 = new int [ n + 1 ] ; int [ ] dp2 = new int [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { dp1 [ i ] = 0 ; dp2 [ i ] = 0 ; } Console . WriteLine ( " Diameter ▁ of ▁ the ▁ given ▁ tree ▁ is ▁ " + dfs ( 1 , 1 , dp1 , dp2 , adj ) ) ; } }