text: Sqrt ( or Square Root ) Decomposition | Set 2 ( LCA of Tree in O ( sqrt ( height ) ) time ) | Naive C # implementation to find LCA in a tree . ; Stores depth for each node ; Stores first parent for each node ; Marking parent for each node ; Marking depth for each node ; Propogating marking down the tree ; A dummy node ; Precalclating 1 ) depth . 2 ) parent . for each node ; Time Complexity : O ( Height of tree ) recursively jumps one node above till both the nodes become equal ; Driver Code ; Adding edges to the tree
code: using System ; using System . Collections ; class GFG { static int MAXN = 1001 ; static int [ ] depth = new int [ MAXN ] ; static int [ ] parent = new int [ MAXN ] ; static ArrayList [ ] adj = new ArrayList [ MAXN ] ; static void addEdge ( int u , int v ) { adj [ u ] . Add ( v ) ; adj [ v ] . Add ( u ) ; } static void dfs ( int cur , int prev ) { parent [ cur ] = prev ; depth [ cur ] = depth [ prev ] + 1 ; for ( int i = 0 ; i < adj [ cur ] . Count ; i ++ ) if ( ( int ) adj [ cur ] [ i ] != prev ) dfs ( ( int ) adj [ cur ] [ i ] , cur ) ; } static void preprocess ( ) { depth [ 0 ] = - 1 ; dfs ( 1 , 0 ) ; } static int LCANaive ( int u , int v ) { if ( u == v ) return u ; if ( depth [ u ] > depth [ v ] ) { int temp = u ; u = v ; v = temp ; } v = parent [ v ] ; return LCANaive ( u , v ) ; } public static void Main ( string [ ] args ) { for ( int i = 0 ; i < MAXN ; i ++ ) adj [ i ] = new ArrayList ( ) ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 1 , 4 ) ; addEdge ( 2 , 5 ) ; addEdge ( 2 , 6 ) ; addEdge ( 3 , 7 ) ; addEdge ( 4 , 8 ) ; addEdge ( 4 , 9 ) ; addEdge ( 9 , 10 ) ; addEdge ( 9 , 11 ) ; addEdge ( 7 , 12 ) ; addEdge ( 7 , 13 ) ; preprocess ( ) ; Console . WriteLine ( " LCA ( 11 , ▁ 8 ) ▁ : ▁ " + LCANaive ( 11 , 8 ) ) ; Console . WriteLine ( " LCA ( 3 , ▁ 13 ) ▁ : ▁ " + LCANaive ( 3 , 13 ) ) ; } }