Sqrt ( or Square Root ) Decomposition | Set 2 ( LCA of Tree in O ( sqrt ( height ) ) time ) | Javascript program to find LCA using Sqrt decomposition ; Block size = Math . sqrt ( height ) ; Stores depth for each node ; Stores first parent for each node ; Stores first ancestor in previous block ; Precalculating the required parameters associated with every node ; Marking depth of cur node ; Marking parent of cur node ; Making jump_parent of cur node ; If it is first node of the block then its jump_parent is its cur parent ; If it is not the first node of this block then its jump_parent is jump_parent of its parent ; Propogating the marking down the subtree ; Using sqrt decomposition trick ; Maintaining depth [ v ] > depth [ u ] ; Climb to its jump parent ; u and v have same jump_parent ; Precalclating 1 ) depth . 2 ) parent . 3 ) jump_parent for each node ; Driver code ; Adding edges to the tree ; Here we are directly taking height = 4 according to the given tree but we can pre - calculate height = max depth in one more dfs
let MAXN = 1001 ; let block_sz ; let depth = new Array ( MAXN ) ; let parent = new Array ( MAXN ) ; let jump_parent = new Array ( MAXN ) ; let adj = new Array ( MAXN ) ; function addEdge ( u , v ) { adj [ u ] . push ( v ) ; adj [ v ] . push ( u ) ; } function LCANaive ( u , v ) { if ( u == v ) return u ; if ( depth [ u ] > depth [ v ] ) { let t = u ; u = v ; v = t ; } v = parent [ v ] ; return LCANaive ( u , v ) ; } function dfs ( cur , prev ) { depth [ cur ] = depth [ prev ] + 1 ; parent [ cur ] = prev ; if ( depth [ cur ] % block_sz == 0 ) jump_parent [ cur ] = parent [ cur ] ; else jump_parent [ cur ] = jump_parent [ prev ] ; for ( let i = 0 ; i < adj [ cur ] . length ; ++ i ) if ( adj [ cur ] [ i ] != prev ) dfs ( adj [ cur ] [ i ] , cur ) ; } function LCASQRT ( u , v ) { while ( jump_parent [ u ] != jump_parent [ v ] ) { if ( depth [ u ] > depth [ v ] ) { let t = u ; u = v ; v = t ; } v = jump_parent [ v ] ; } return LCANaive ( u , v ) ; } function preprocess ( height ) { block_sz = parseInt ( Math . sqrt ( height ) , 10 ) ; depth [ 0 ] = - 1 ; dfs ( 1 , 0 ) ; } for ( let i = 0 ; i < adj . length ; i ++ ) adj [ i ] = [ ] ; 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 ) ; let height = 4 ; preprocess ( height ) ; document . write ( " " + LCASQRT ( 11 , 8 ) + " " ) ; document . write ( " " + LCASQRT ( 3 , 13 ) + " " ) ;