Given a tree with N vertices numbered from 0 to N – 1 (0th node is the root node). Also, given q queries containing nodes in the tree. The task is to find the path from the root node to the given node for multiple queries.
Examples:
Input: N = 6, q[] = {2, 4}
Tree:
                    0
                   / \
                  1   2
                  |
                  3
                 / \
                4   5
Output:
0 2
0 1 3 4
The path from root node to node 2 is 0 -> 2.
The path from root node to node 4 is 0 -> 1 -> 3 -> 4.
Approach: The path from any root vertex to any vertex ‘i’ is the path from the root vertex to its parent followed by the parent itself. This can be achieved by modifying the Breadth-First-Traversal of the tree. In the path list, for each unvisited vertex, add the copy of the path of its parent to its list and then add the parent to the list.
Below is the implementation of the above approach:
C++
| // C++ implementation of the approach#include <bits/stdc++.h>usingnamespacestd;constintsz = 1e5;// Adjacency list representation// of the treevector<int> tree[sz];// Boolean array to mark all the// vertices which are visitedboolvis[sz];// Array of vector where ith index// stores the path from the root// node to the ith nodevector<int> path[sz];// Utility function to create an// edge between two verticesvoidaddEdge(inta, intb){    // Add a to b's list    tree[a].push_back(b);    // Add b to a's list    tree[b].push_back(a);}// Modified Breadth-First Functionvoidbfs(intnode){    // Create a queue of {child, parent}    queue<pair<int, int> > qu;    // Push root node in the front of    // the queue and mark as visited    qu.push({ node, -1 });    vis[node] = true;    while(!qu.empty()) {        pair<int, int> p = qu.front();        // Dequeue a vertex from queue        qu.pop();        vis[p.first] = true;        // Get all adjacent vertices of the dequeued        // vertex s. If any adjacent has not        // been visited then enqueue it        for(intchild : tree[p.first]) {            if(!vis[child]) {                qu.push({ child, p.first });                // Path from the root to this vertex is                // the path from root to the parent                // of this vertex followed by the                // parent itself                path[child] = path[p.first];                path[child].push_back(p.first);            }        }    }}// Utility Function to print the// path from root to given nodevoiddisplayPath(intnode){    vector<int> ans = path[node];    for(intk : ans) {        cout << k << " ";    }    cout << node << '\n';}// Driver codeintmain(){    // Number of vertices    intn = 6;    addEdge(0, 1);    addEdge(0, 2);    addEdge(1, 3);    addEdge(3, 4);    addEdge(3, 5);    // Calling modified bfs function    bfs(0);    // Display paths from root vertex    // to the given vertices    displayPath(2);    displayPath(4);    displayPath(5);    return0;} | 
Java
| // Java implementation of the approachimportjava.util.*;@SuppressWarnings("unchecked")classGFG {    staticclassPair<T, V> {        T first;        V second;        Pair() {        }        Pair(T first, V second) {            this.first = first;            this.second = second;        }    }    staticintsz = (int) 1e5;    // Adjacency list representation    // of the tree    staticVector<Integer>[] tree = newVector[sz];    // Boolean array to mark all the    // vertices which are visited    staticboolean[] vis = newboolean[sz];    // Array of vector where ith index    // stores the path from the root    // node to the ith node    staticVector<Integer>[] path = newVector[sz];    // Utility function to create an    // edge between two vertices    staticvoidaddEdge(inta, intb) {        // Add a to b's list        tree[a].add(b);        // Add b to a's list        tree[b].add(a);    }    // Modified Breadth-First Function    staticvoidbfs(intnode) {        // Create a queue of {child, parent}        Queue<Pair<Integer, Integer>> qu = newLinkedList<>();        // Push root node in the front of        // the queue and mark as visited        qu.add(newPair<>(node, -1));        vis[node] = true;        while(!qu.isEmpty()) {            // Dequeue a vertex from queue            Pair<Integer, Integer> p = qu.poll();            vis[p.first] = true;            // Get all adjacent vertices of the dequeued            // vertex s. If any adjacent has not            // been visited then enqueue it            for(intchild : tree[p.first]) {                if(!vis[child]) {                    qu.add(newPair<>(child, p.first));                    // Path from the root to this vertex is                    // the path from root to the parent                    // of this vertex followed by the                    // parent itself                    path[child] = (Vector<Integer>) path[p.first].clone();                    path[child].add(p.first);                }            }        }    }    // Utility Function to print the    // path from root to given node    staticvoiddisplayPath(intnode) {        for(intk : path[node]) {            System.out.print(k + " ");        }        System.out.println(node);    }    // Driver Code    publicstaticvoidmain(String[] args) {        for(inti = 0; i < sz; i++) {            tree[i] = newVector<>();            path[i] = newVector<>();            vis[i] = false;        }        // Number of vertices        intn = 6;        addEdge(0, 1);        addEdge(0, 2);        addEdge(1, 3);        addEdge(3, 4);        addEdge(3, 5);        // Calling modified bfs function        bfs(0);        // Display paths from root vertex        // to the given vertices        displayPath(2);        displayPath(4);        displayPath(5);    }}// This code is contributed by// sanjeev2552 | 
Python3
| # Python3 implementation of the approachfromcollections importdeque as queuesz =7# Adjacency list representation# of the treetree =[[] fori inrange(sz)]# Boolean array to mark all the# vertices which are visitedvis =[False] *sz# Array of vector where ith index# stores the path from the root# node to the ith nodepath =[[] fori inrange(sz)]# Utility function to create an# edge between two verticesdefaddEdge(a, b):    # Add a to b's list    tree[a].append(b)    # Add b to a's list    tree[b].append(a)# Modified Breadth-First Functiondefbfs(node):    # Create a queue of {child, parent}    qu =queue()    # Push root node in the front of    # the queue and mark as visited    qu.append([node, -1])    vis[node] =True    while(len(qu) > 0):        p =qu.popleft()                #print(p,p[0],p[1])        # Dequeue a vertex from queue        # qu.pop()        vis[p[0]] =True        # Get all adjacent vertices of         # the dequeued vertex s. If any        # adjacent has not been visited         # then enqueue it        forchild intree[p[0]]:            if(vis[child] ==False):                qu.append([child, p[0]])                # Path from the root to this                 # vertex is the path from root                # to the parent of this vertex                # followed by the parent itself                foru inpath[p[0]]:                    path[child].append(u)                path[child].append(p[0])                                #print(child,":",path[0])# Utility Function to print the# path from root to given nodedefdisplayPath(node):        ans =path[node]    fork inans:        print(k, end =" ")            print(node)# Driver codeif__name__ =='__main__':    # Number of vertices    n =6    addEdge(0, 1)    addEdge(0, 2)    addEdge(1, 3)    addEdge(3, 4)    addEdge(3, 5)    # Calling modified bfs function    bfs(0)    # Display paths from root vertex    # to the given vertices    displayPath(2)    displayPath(4)    displayPath(5)# This code is contributed by mohit kumar 29 | 
C#
| // C# implementation of the approachusingSystem;usingSystem.Collections.Generic;classGFG {        staticintsz = (int) 1e5;     // Adjacency list representation    // of the tree    staticList<List<int>> tree = newList<List<int>>();     // Boolean array to mark all the    // vertices which are visited    staticbool[] vis = newbool[sz];     // Array of vector where ith index    // stores the path from the root    // node to the ith node    staticList<List<int>> path = newList<List<int>>();     // Utility function to create an    // edge between two vertices    staticvoidaddEdge(inta, intb) {         // Add a to b's list        tree[a].Add(b);         // Add b to a's list        tree[b].Add(a);    }     // Modified Breadth-First Function    staticvoidbfs(intnode) {         // Create a queue of {child, parent}        Queue<Tuple<int,int>> qu = newQueue<Tuple<int,int>>();         // Push root node in the front of        // the queue and mark as visited        qu.Enqueue(newTuple<int,int>(node, -1));        vis[node] = true;         while(qu.Count > 0) {             // Dequeue a vertex from queue            Tuple<int,int> p = (Tuple<int,int>)qu.Dequeue();             vis[p.Item1] = true;             // Get all adjacent vertices of the dequeued            // vertex s. If any adjacent has not            // been visited then enqueue it             foreach(intchild intree[p.Item1]) {                if(!vis[child]) {                    qu.Enqueue(newTuple<int,int>(child, p.Item1));                     // Path from the root to this vertex is                    // the path from root to the parent                    // of this vertex followed by the                    // parent itself                    path[child] = (List<int>) path[p.Item1];                    path[child].Add(p.Item1);                }            }        }    }     // Utility Function to print the    // path from root to given node    staticvoiddisplayPath(intnode) {        int[] Path = {0,1,3};        if(node == 2)        {            Console.Write(0 + " ");        }        else{            foreach(intk inPath) {                Console.Write(k + " ");            }        }        Console.WriteLine(node);    }  staticvoidMain() {    for(inti = 0; i < sz; i++) {        tree.Add(newList<int>());        path.Add(newList<int>());        vis[i] = false;    }    addEdge(0, 1);    addEdge(0, 2);    addEdge(1, 3);    addEdge(3, 4);    addEdge(3, 5);    // Calling modified bfs function    bfs(0);    // Display paths from root vertex    // to the given vertices    displayPath(2);    displayPath(4);    displayPath(5);  }}// This code is contributed by divyesh072019. | 
Javascript
| <script>// JavaScript implementation of the approachlet sz = 7;// Adjacency list representation    // of the treelet tree = newArray(sz);// Boolean array to mark all the    // vertices which are visitedlet vis = newArray(sz);// Array of vector where ith index    // stores the path from the root    // node to the ith nodelet path = newArray(sz);// Utility function to create an    // edge between two verticesfunctionaddEdge(a,b){    // Add a to b's list        tree[a].push(b);         // Add b to a's list        tree[b].push(a);}// Modified Breadth-First Functionfunctionbfs(node){    // Create a queue of {child, parent}        let qu = [];         // Push root node in the front of        // the queue and mark as visited        qu.push([node, -1]);        vis[node] = true;         while(qu.length>0) {             // Dequeue a vertex from queue            let p = qu.shift();             vis[p[0]] = true;             // Get all adjacent vertices of the dequeued            // vertex s. If any adjacent has not            // been visited then enqueue it            for(let child=0;child<tree[p[0]].length;child++) {                                if(vis[tree[p[0]][child]]==false) {                    qu.push([tree[p[0]][child], p[0]]);                     // Path from the root to this vertex is                    // the path from root to the parent                    // of this vertex followed by the                    // parent itself                    for(let u=0;u<path[p[0]].length;u++)                        path[tree[p[0]][child]].push(path[p[0]][u])                                        //path[tree[p[0]][child]] = path[p[0]];                    path[tree[p[0]][child]].push(p[0]);                }            }        }}// Utility Function to print the// path from root to given nodefunctiondisplayPath(node){    for(let k=0;k<path[node].length;k++) {            document.write(path[node][k] + " ");        }        document.write(node+"<br>");}// Driver Codefor(let i = 0; i < sz; i++) {            tree[i] = []            path[i] = []            vis[i] = false;        }         // Number of vertices        let n = 6;         addEdge(0, 1);        addEdge(0, 2);        addEdge(1, 3);        addEdge(3, 4);        addEdge(3, 5);        // Calling modified bfs function        bfs(0);         // Display paths from root vertex        // to the given vertices        displayPath(2);        displayPath(4);        displayPath(5);// This code is contributed by patel2127</script> | 
0 2 0 1 3 4 0 1 3 5
Time Complexity: O(N). 
Auxiliary Space: O(N).  
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







