Check if two nodes are on same path in a tree | Set 2 - GeeksforGeeks

21 Jun, 2021
Given two nodes of a binary tree v1 and v2, the task is to check if two nodes are on the same path in a tree. Example:  
Input:  v1 = 1, v2 = 5
       1
    /  |  \
   2   3   4
  /    |    \
 5     6     7
 
Output: Yes
Explanation:
Both nodes 1 and 5
lie in the path 1 -> 2 -> 5.

Input: v1 = 2, v2 = 6
       1
    /  |  \
   2   3   4
  /    |    \
 5     6     7

Output: NO
DFS Approach: Refer to Check if two nodes are on same path in a tree for the DFS approach.LCA Approach: The idea is to use Lowest Common Ancestor. Find the LCA of the given vertices v1 and v2. If the LCA is equal to any of the given two vertices, print Yes. Otherwise, print No.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if two nodes// are on same path in a tree without// using any extra space#include <bits/stdc++.h>using namespace std; // Function to filter// the return Valuesint filter(int x, int y, int z){    if (x != -1 && y != -1) {        return z;    }    return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notint samePathUtil(int mtrx[][7], int vrtx,                 int v1, int v2, int i){    int ans = -1;     // Condition to check    // if any vertex    // is equal to given two    // vertex or not    if (i == v1 || i == v2)        return i;     for (int j = 0; j < vrtx; j++) {         // Check if the current        // position has 1        if (mtrx[i][j] == 1) {            // Recursive call            ans                = filter(ans,                         samePathUtil(mtrx,                                      vrtx,                                      v1,                                      v2,                                      j),                         i);        }    }     // Return LCA    return ans;} // Function to check if nodes// lies on same path or notbool isVertexAtSamePath(int mtrx[][7],                        int vrtx, int v1,                        int v2, int i){    int lca = samePathUtil(mtrx,                           vrtx, v1 - 1,                           v2 - 1, i);     if (lca == v1 - 1 || lca == v2 - 1)        return true;     return false;} // Driver Programint main(){    int vrtx = 7, edge = 6;    int mtrx[7][7] = {        { 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 }     };     int v1 = 1, v2 = 5;     if (isVertexAtSamePath(mtrx,                           vrtx, v1,                           v2, 0))        cout << "Yes";     else        cout << "No";     return 0;}
// Java program to check if two nodes// are on same path in a tree without// using any extra spaceclass GFG{ // Function to filter// the return Valuesstatic int filter(int x, int y, int z){    if (x != -1 && y != -1)    {        return z;    }    return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notstatic int samePathUtil(int mtrx[][], int vrtx,                        int v1, int v2, int i){    int ans = -1;     // Condition to check    // if any vertex    // is equal to given two    // vertex or not    if (i == v1 || i == v2)        return i;     for(int j = 0; j < vrtx; j++)    {                 // Check if the current        // position has 1        if (mtrx[i][j] == 1)        {                         // Recursive call            ans = filter(ans, samePathUtil(                         mtrx, vrtx, v1,                         v2, j), i);        }    }     // Return LCA    return ans;} // Function to check if nodes// lies on same path or notstatic boolean isVertexAtSamePath(int mtrx[][],                                  int vrtx, int v1,                                  int v2, int i){    int lca = samePathUtil(mtrx, vrtx, v1 - 1,                                       v2 - 1, i);                                            if (lca == v1 - 1 || lca == v2 - 1)        return true;     return false;} // Driver codepublic static void main(String[] args){    int vrtx = 7;    int 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 } };     int v1 = 1, v2 = 5;     if (isVertexAtSamePath(mtrx, vrtx,                           v1, v2, 0))        System.out.print("Yes");    else        System.out.print("No");}} // This code is contributed by Rajput-Ji
# Python3 program to check if two nodes# are on same path in a tree without# using any extra space # Function to filter# the return Valuesdef filter(x, y, z):         if (x != -1 and y != -1):        return z         return y if x == -1 else x # Utility function to check if nodes# are on same path or notdef samePathUtil(mtrx, vrtx, v1, v2, i):         ans = -1     # Condition to check    # if any vertex    # is equal to given two    # vertex or not    if (i == v1 or i == v2):        return i         for j in range(0, vrtx):                 # Check if the current        # position has 1        if (mtrx[i][j] == 1):                         # Recursive call            ans = filter(ans,                         samePathUtil(mtrx, vrtx,                                   v1, v2, j), i)             # Return LCA    return ans # Function to check if nodes# lies on same path or notdef isVertexAtSamePath(mtrx, vrtx, v1, v2, i):         lca = samePathUtil(mtrx, vrtx, v1 - 1,                                   v2 - 1, i)     if (lca == v1 - 1 or lca == v2 - 1):        return True     return False # Driver codevrtx = 7edge = 6 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 ] ] v1 = 1v2 = 5 if (isVertexAtSamePath(mtrx, vrtx, v1, v2, 0)):    print("Yes")else:    print("No") # This code is contributed by sanjoy_62
// C# program to check if two nodes// are on same path in a tree without// using any extra spaceusing System;class GFG{ // Function to filter// the return Valuesstatic int filter(int x, int y, int z){    if (x != -1 && y != -1)    {        return z;    }    return x == -1 ? y : x;} // Utility function to check if nodes// are on same path or notstatic int samePathUtil(int [,]mtrx, int vrtx,                        int v1, int v2, int i){    int ans = -1;     // Condition to check    // if any vertex    // is equal to given two    // vertex or not    if (i == v1 || i == v2)        return i;     for(int j = 0; j < vrtx; j++)    {                 // Check if the current        // position has 1        if (mtrx[i,j] == 1)        {                         // Recursive call            ans = filter(ans, samePathUtil(                         mtrx, vrtx, v1,                         v2, j), i);        }    }     // Return LCA    return ans;} // Function to check if nodes// lies on same path or notstatic bool isVertexAtSamePath(int [,]mtrx,                               int vrtx, int v1,                               int v2, int i){    int lca = samePathUtil(mtrx, vrtx, v1 - 1,                                       v2 - 1, i);                                            if (lca == v1 - 1 || lca == v2 - 1)        return true;     return false;} // Driver codepublic static void Main(String[] args){    int vrtx = 7;    int [,]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 } };     int v1 = 1, v2 = 5;     if (isVertexAtSamePath(mtrx, vrtx,                           v1, v2, 0))        Console.Write("Yes");    else        Console.Write("No");}} // This code is contributed by sapnasingh4991
<script>    // Javascript program to check if two nodes    // are on same path in a tree without    // using any extra space         // Function to filter    // the return Values    function filter(x, y, z)    {        if (x != -1 && y != -1)        {            return z;        }        return x == -1 ? y : x;    }     // Utility function to check if nodes    // are on same path or not    function samePathUtil(mtrx, vrtx, v1, v2, i)    {        let ans = -1;         // Condition to check        // if any vertex        // is equal to given two        // vertex or not        if (i == v1 || i == v2)            return i;         for(let j = 0; j < vrtx; j++)        {             // Check if the current            // position has 1            if (mtrx[i][j] == 1)            {                 // Recursive call                ans = filter(ans, samePathUtil(                             mtrx, vrtx, v1,                             v2, j), i);            }        }         // Return LCA        return ans;    }     // Function to check if nodes    // lies on same path or not    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("Yes");    else        document.write("No");     // This code is contributed by mukesh07.   </script>
Yes
 
Time Complexity: O(N) Auxiliary Space: O(1) 
Rajput-Ji
sapnasingh4991
sanjoy_62
mukesh07
interview-preparation
LCA
Samsung
Competitive Programming
Data Structures
Placements
Tree
Samsung
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
7 Best Coding Challenge Websites in 2020
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
How to Start Learning DSA?