Check if two nodes are on same path in a tree | Set 2 | Function to filter the return Values ; Utility function to check if nodes are on same path or not ; Condition to check if any vertex is equal to given two vertex or not ; Check if the current position has 1 ; Recursive call ; Return LCA ; Function to check if nodes lies on same path or not ; Driver code
function filter ( x , y , z ) { if ( x != - 1 && y != - 1 ) { return z ; } return x == - 1 ? y : x ; } function samePathUtil ( mtrx , vrtx , v1 , v2 , i ) { let ans = - 1 ; if ( i == v1 i == v2 ) return i ; for ( let j = 0 ; j < vrtx ; j ++ ) { if ( mtrx [ i ] [ j ] == 1 ) { ans = filter ( ans , samePathUtil ( mtrx , vrtx , v1 , v2 , j ) , i ) ; } } return ans ; } function isVertexAtSamePath ( mtrx , vrtx , v1 , v2 , i ) { let lca = samePathUtil ( mtrx , vrtx , v1 - 1 , v2 - 1 , i ) ; if ( lca == v1 - 1 lca == v2 - 1 ) return true ; return false ; } let vrtx = 7 ; let mtrx = [ [ 0 , 1 , 1 , 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ] ; let v1 = 1 , v2 = 5 ; if ( isVertexAtSamePath ( mtrx , vrtx , v1 , v2 , 0 ) ) document . write ( " " ) ; else document . write ( " " ) ;