Query for ancestor-descendant relationship in a tree

01 Jul, 2021
Given a rooted tree with N vertices and N-1 edges. We will be given many pairs of vertices u and v, we need to tell whether u is an ancestor of v or not. Given tree will be rooted at the vertex with index 0. 
Examples:
u = 1    v = 6
we can see from above tree that node 
1 is ancestor of node 6 so the answer 
will be yes.

u = 1    v = 7
we can see from above tree that node 1 
is not an ancestor of node 7 so the
answer will be no.
We can solve this problem using depth first search of the tree. While doing dfs we can observe a relation between the order in which we visit a node and its ancestors. If we assign in-time and out-time to each node when entering and leaving that node in dfs then we can see that for each pair of ancestor-descendant the in-time of ancestor is less than that of descendant and out-time of ancestor is more than that of descendant, so using this relation we can find the result for each pair of node in O(1) time. 
So time complexity for preprocessing will be O(N) and for the query it will be O(1). 
C++
Java
Python3
C#
Javascript
// C++ program to query whether two node has// ancestor-descendant relationship or not#include <bits/stdc++.h>using namespace std; // Utility dfs method to assign in and out time// to each nodevoid dfs(vector<int> g[], int u, int parent,         int timeIn[], int timeOut[], int& cnt){    // assign In-time to node u    timeIn[u] = cnt++;     // call dfs over all neighbors except parent    for (int i = 0; i < g[u].size(); i++) {        int v = g[u][i];        if (v != parent)            dfs(g, v, u, timeIn, timeOut, cnt);    }     // assign Out-time to node u    timeOut[u] = cnt++;} // method to preprocess all nodes for assigning timevoid preProcess(int edges[][2], int V, int timeIn[],                int timeOut[]){    vector<int> g[V];     // construct array of vector data structure    // for tree    for (int i = 0; i < V - 1; i++) {        int u = edges[i][0];        int v = edges[i][1];         g[u].push_back(v);        g[v].push_back(u);    }     int cnt = 0;     // call dfs method from root    dfs(g, 0, -1, timeIn, timeOut, cnt);} // method returns "yes" if u is a ancestor// node of vstring isAncestor(int u, int v, int timeIn[],                  int timeOut[]){    bool b = (timeIn[u] <= timeIn[v] &&             timeOut[v] <= timeOut[u]);    return (b ? "yes" : "no");} // Driver code to test abovea methodsint main(){    int edges[][2] = {        { 0, 1 },        { 0, 2 },        { 1, 3 },        { 1, 4 },        { 2, 5 },        { 4, 6 },        { 5, 7 }    };     int E = sizeof(edges) / sizeof(edges[0]);    int V = E + 1;     int timeIn[V], timeOut[V];    preProcess(edges, V, timeIn, timeOut);     int u = 1;    int v = 6;    cout << isAncestor(u, v, timeIn, timeOut) << endl;     u = 1;    v = 7;    cout << isAncestor(u, v, timeIn, timeOut) << endl;     return 0;}
// Java program to query whether two node has// ancestor-descendant relationship or notimport java.util.Vector; class GFG{  static int cnt;   // Utility dfs method to assign in and out time  // to each node  static void dfs(Vector<Integer> []g, int u, int parent,                  int []timeIn, int []timeOut)  {     // Assign In-time to node u    timeIn[u] = cnt++;     // Call dfs over all neighbors except parent    for(int i = 0; i < g[u].size(); i++)    {      int v = g[u].get(i);             if (v != parent)        dfs(g, v, u, timeIn, timeOut);    }     // Assign Out-time to node u    timeOut[u] = cnt++;  }   // Method to preprocess all nodes for assigning time  static void preProcess(int [][]edges, int V,                         int []timeIn, int []timeOut)  {    @SuppressWarnings("unchecked")    Vector<Integer> []g = new Vector[V];    for (int i = 0; i < g.length; i++)      g[i] = new Vector<Integer>();     // Conarray of vector data structure    // for tree    for(int i = 0; i < V - 1; i++)    {      int u = edges[i][0];      int v = edges[i][1];      g[u].add(v);      g[v].add(u);    }    cnt = 0;     // Call dfs method from root    dfs(g, 0, -1, timeIn, timeOut);  }   // Method returns "yes" if u is a ancestor  // node of v  static String isAncestor(int u, int v, int []timeIn,                           int []timeOut)  {    boolean b = (timeIn[u] <= timeIn[v] &&                 timeOut[v] <= timeOut[u]);    return (b ? "yes" : "no");  }   // Driver code     public static void main(String[] args)  {    int edges[][] = { { 0, 1 },                     { 0, 2 },                     { 1, 3 },                     { 1, 4 },                     { 2, 5 },                     { 4, 6 },                     { 5, 7 } };       int E = edges.length;    int V = E + 1;      int []timeIn = new int[V];    int []timeOut = new int[V];      preProcess(edges, V, timeIn, timeOut);       int u = 1;    int v = 6;    System.out.println(isAncestor(u, v, timeIn,                                  timeOut));       u = 1;    v = 7;    System.out.println(isAncestor(u, v, timeIn,                                  timeOut));  }} // This code is contributed by gauravrajput1
# Python program to query whether two node has# ancestor-descendant relationship or not cnt = 0 # Utility dfs method to assign in and out time# to each nodedef dfs(g: list, u: int, parent: int, timeIn: list, timeOut: list):    global cnt     # assign In-time to node u    timeIn[u] = cnt    cnt += 1     # call dfs over all neighbors except parent    for i in range(len(g[u])):        v = g[u][i]        if v != parent:            dfs(g, v, u, timeIn, timeOut)     # assign Out-time to node u    timeOut[u] = cnt    cnt += 1 # method to preprocess all nodes for assigning timedef preProcess(edges: list, V: int, timeIn: list, timeOut: list):    global cnt    g = [[] for i in range(V)]     # construct array of vector data structure    # for tree    for i in range(V - 1):        u = edges[i][0]        v = edges[i][1]         g[u].append(v)        g[v].append(u)     cnt = 0     # call dfs method from root    dfs(g, 0, -1, timeIn, timeOut) # method returns "yes" if u is a ancestor# node of vdef isAncestor(u: int, v: int, timeIn: list, timeOut: list) -> str:    b = timeIn[u] <= timeIn[u] and timeOut[v] <= timeOut[u]    return "yes" if b else "no" # Driver Codeif __name__ == "__main__":    edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (4, 6), (5, 7)]    E = len(edges)    V = E + 1     timeIn = [0] * V    timeOut = [0] * V    preProcess(edges, V, timeIn, timeOut)     u = 1    v = 6    print(isAncestor(u, v, timeIn, timeOut))     u = 1    v = 7    print(isAncestor(u, v, timeIn, timeOut)) # This code is contributed by# sanjeev2552
// C# program to query whether two node has// ancestor-descendant relationship or notusing System;using System.Collections; class GFG{ // Utility dfs method to assign in and out time// to each nodestatic void dfs(ArrayList []g, int u, int parent,                int []timeIn, int []timeOut,                ref int cnt){         // Assign In-time to node u    timeIn[u] = cnt++;      // Call dfs over all neighbors except parent    for(int i = 0; i < g[u].Count; i++)    {        int v = (int)g[u][i];                 if (v != parent)            dfs(g, v, u, timeIn, timeOut, ref cnt);    }      // Assign Out-time to node u    timeOut[u] = cnt++;}  // Method to preprocess all nodes for assigning timestatic void preProcess(int [,]edges, int V,                       int []timeIn, int []timeOut){    ArrayList []g = new ArrayList[V];         for(int i = 0; i < V; i++)    {        g[i] = new ArrayList();    }      // Construct array of vector data structure    // for tree    for(int i = 0; i < V - 1; i++)    {        int u = edges[i, 0];        int v = edges[i, 1];          g[u].Add(v);        g[v].Add(u);    }      int cnt = 0;      // Call dfs method from root    dfs(g, 0, -1, timeIn, timeOut, ref cnt);}  // Method returns "yes" if u is a ancestor// node of vstatic string isAncestor(int u, int v, int []timeIn,                                       int []timeOut){    bool b = (timeIn[u] <= timeIn[v] &&             timeOut[v] <= timeOut[u]);    return (b ? "yes" : "no");}     // Driver code   static void Main(){    int [,]edges = { { 0, 1 },                     { 0, 2 },                     { 1, 3 },                     { 1, 4 },                     { 2, 5 },                     { 4, 6 },                     { 5, 7 } };         int E = edges.GetLength(0);    int V = E + 1;         int []timeIn = new int[V];    int []timeOut = new int[V];         preProcess(edges, V, timeIn, timeOut);         int u = 1;    int v = 6;    Console.Write(isAncestor(u, v, timeIn,                             timeOut) + "\n");         u = 1;    v = 7;    Console.Write(isAncestor(u, v, timeIn,                             timeOut) + "\n");}} // This code is contributed by rutvik_56
<script> // Javascript program to query whether// two node has ancestor-descendant// relationship or notlet cnt; // Utility dfs method to assign in and out time// to each nodefunction dfs(g, u, parent, timeIn, timeOut){         // Assign In-time to node u    timeIn[u] = cnt++;         // Call dfs over all neighbors except parent    for(let i = 0; i < g[u].length; i++)    {        let v = g[u][i];              if (v != parent)            dfs(g, v, u, timeIn, timeOut);    }         // Assign Out-time to node u    timeOut[u] = cnt++;} // Method to preprocess all nodes for assigning timefunction preProcess(edges, V, timeIn, timeOut){    let g = new Array(V);    for(let i = 0; i < g.length; i++)        g[i] = [];         // Conarray of vector data structure    // for tree    for(let i = 0; i < V - 1; i++)    {        let u = edges[i][0];        let v = edges[i][1];        g[u].push(v);        g[v].push(u);    }    cnt = 0;         // Call dfs method from root    dfs(g, 0, -1, timeIn, timeOut);} // Method returns "yes" if u is a ancestor// node of vfunction isAncestor(u, v, timeIn, timeOut){    let b = (timeIn[u] <= timeIn[v] &&             timeOut[v] <= timeOut[u]);    return (b ? "yes" : "no");} // Driver codelet edges = [ [ 0, 1 ], [ 0, 2 ],              [ 1, 3 ], [ 1, 4 ],              [ 2, 5 ], [ 4, 6 ],              [ 5, 7 ] ];  let E = edges.length;let V = E + 1; let timeIn = new Array(V);let timeOut = new Array(V); preProcess(edges, V, timeIn, timeOut); let u = 1;let v = 6;document.write(isAncestor(u, v, timeIn,                          timeOut) + "</br>");  u = 1;v = 7;document.write(isAncestor(u, v, timeIn,                          timeOut));                           // This code is contributed by divyeshrabadiya07 </script>
Output: 
yes
no
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
sanjeev2552
rutvik_56
GauravRajput1
divyeshrabadiya07
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
A program to check if a binary tree is BST or not
Decision Tree
Top 50 Tree Coding Problems for Interviews
Segment Tree | Set 1 (Sum of given range)
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Lowest Common Ancestor in a Binary Search Tree.