text: Sqrt ( or Square Root ) Decomposition | Set 2 ( LCA of Tree in O ( sqrt ( height ) ) time ) | Naive Java 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: import java . io . * ; import java . util . * ; class GFG { static int MAXN = 1001 ; static int [ ] depth = new int [ MAXN ] ; static int [ ] parent = new int [ MAXN ] ; @ SuppressWarnings ( " unchecked " ) static Vector < Integer > [ ] adj = new Vector [ MAXN ] ; static { for ( int i = 0 ; i < MAXN ; i ++ ) adj [ i ] = new Vector < > ( ) ; } 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 ] . size ( ) ; i ++ ) if ( adj [ cur ] . elementAt ( i ) != prev ) dfs ( adj [ cur ] . elementAt ( 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 ) { 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 ( ) ; System . out . println ( " LCA ( 11,8 ) ▁ : ▁ " + LCANaive ( 11 , 8 ) ) ; System . out . println ( " LCA ( 3,13 ) ▁ : ▁ " + LCANaive ( 3 , 13 ) ) ; } }