Given a tree of N nodes and N-1 edges. The task is to print the DFS of the subtree of a given node for multiple queries. The DFS must include the given node as the root of the subtree.
In the above tree, if 1 is given as the node, then the DFS of subtree will be 1 2 4 6 7 5 3.
If 2 is given as the node, then the DFS of the subtree will be 2 4 6 7 5..Â
Approach:Â
- Add the edges between the nodes in an adjacency list.
- Call DFS function to generate the DFS of the complete tree.
- Use a under[] array to store the height of the subtree under the given node including the node.
- In the DFS function, keep incrementing the size of subtree on every recursive call.
- Mark the node index in the DFS of complete using hashing.
- The DFS of a subtree of a node will always be a contiguous subarray starting from the node(say index ind) to (ind+height of subtree).
- Get the index of node which has been stored using hashing and print the nodes from original DFS till index = ind + height of subtree which has been stored in under[node].
Below is the implementation of the above approach. Â
C++
// C++ program for Queries// for DFS of subtree of a node in a tree#include <bits/stdc++.h>using namespace std;const int N = 100000;Â
// Adjacency list to store the// tree nodes connectionvector<int> v[N];Â
// stores the index of node in DFSunordered_map<int, int> mp;Â
// stores the index of node in// original nodevector<int> a;Â
// Function to call DFS and count nodes// under that subtreevoid dfs(int under[], int child, int parent){Â
    // stores the DFS of tree    a.push_back(child);Â
    // height of subtree    under[child] = 1;Â
    // iterate for children    for (auto it : v[child]) {Â
        // if not equal to parent        // so that it does not traverse back        if (it != parent) {Â
            // call DFS for subtree            dfs(under, it, child);Â
            // add the height            under[child] += under[it];        }    }}Â
// Function to print the DFS of subtree of nodevoid printDFSofSubtree(int node, int under[]){Â Â Â Â // index of node in the original DFSÂ Â Â Â int ind = mp[node];Â
    // height of subtree of node    int height = under[node];Â
    cout << "The DFS of subtree " << node << ": ";Â
    // print the DFS of subtree    for (int i = ind; i < ind + under[node]; i++) {        cout << a[i] << " ";    }    cout << endl;}Â
// Function to add edges to a treevoid addEdge(int x, int y){Â Â Â Â v[x].push_back(y);Â Â Â Â v[y].push_back(x);}Â
// Marks the index of node in original DFSvoid markIndexDfs(){Â Â Â Â int size = a.size();Â
    // marks the index    for (int i = 0; i < size; i++) {        mp[a[i]] = i;    }}Â
// Driver Codeint main(){Â Â Â Â int n = 7;Â
    // add edges of a tree    addEdge(1, 2);    addEdge(1, 3);    addEdge(2, 4);    addEdge(2, 5);    addEdge(4, 6);    addEdge(4, 7);Â
    // array to store the height of subtree    // of every node in a tree    int under[n + 1];Â
    // Call the function DFS to generate the DFS    dfs(under, 1, 0);Â
    // Function call to mark the index of node    markIndexDfs();Â
    // Query 1    printDFSofSubtree(2, under);Â
    // Query 1    printDFSofSubtree(4, under);Â
    return 0;} |
Java
// Java program for queries for DFS// of subtree of a node in a treeimport java.util.*;Â
class GFG{Â Â Â Â Â static int N = 100000;Â
// Adjacency list to store the// tree nodes connection@SuppressWarnings("unchecked")static Vector<Integer> []v = new Vector[N];Â
// Stores the index of node in DFSstatic HashMap<Integer,               Integer> mp = new HashMap<Integer,                                         Integer>();Â
// Stores the index of node in// original nodestatic Vector<Integer> a = new Vector<>();Â
// Function to call DFS and count nodes// under that subtreestatic void dfs(int under[], int child,                int parent){         // Stores the DFS of tree    a.add(child);Â
    // Height of subtree    under[child] = 1;Â
    // Iterate for children    for(int it : v[child])    {                 // If not equal to parent so that        // it does not traverse back        if (it != parent)         {                         // Call DFS for subtree            dfs(under, it, child);Â
            // Add the height            under[child] += under[it];        }    }}Â
// Function to print the DFS of subtree of nodestatic void printDFSofSubtree(int node, int under[]){Â Â Â Â Â Â Â Â Â // Index of node in the original DFSÂ Â Â Â int ind = mp.get(node);Â
    // Height of subtree of node    int height = under[node];Â
    System.out.print("The DFS of subtree " +                       node + ": ");Â
    // Print the DFS of subtree    for(int i = ind; i < ind + under[node]; i++)    {        System.out.print(a.get(i) + " ");    }    System.out.println();}Â
// Function to add edges to a treestatic void addEdge(int x, int y){Â Â Â Â v[x].add(y);Â Â Â Â v[y].add(x);}Â
// Marks the index of node in original DFSstatic void markIndexDfs(){Â Â Â Â int size = a.size();Â
    // Marks the index    for(int i = 0; i < size; i++)     {        mp.put(a.get(i), i);    }}Â
// Driver Codepublic static void main(String[] args){    int n = 7;         for(int i = 0; i < v.length; i++)        v[i] = new Vector<Integer>();             // Add edges of a tree    addEdge(1, 2);    addEdge(1, 3);    addEdge(2, 4);    addEdge(2, 5);    addEdge(4, 6);    addEdge(4, 7);Â
    // Array to store the height of    // subtree of every node in a tree    int []under = new int[n + 1];Â
    // Call the function DFS to    // generate the DFS    dfs(under, 1, 0);Â
    // Function call to mark the    // index of node    markIndexDfs();Â
    // Query 1    printDFSofSubtree(2, under);Â
    // Query 1    printDFSofSubtree(4, under);}}Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 program for Queries # for DFS of subtree of a node in a tree N = 100000Â
# Adjacency list to store the # tree nodes connection v = [[]for i in range(N)]Â
# stores the index of node in DFS mp = {}Â
# stores the index of node in # original node a = []Â
# Function to call DFS and count nodes # under that subtree def dfs(under, child, parent):         # stores the DFS of tree     a.append(child)          # height of subtree     under[child] = 1         # iterate for children     for it in v[child]:                 # if not equal to parent         # so that it does not traverse back         if (it != parent):                         # call DFS for subtree             dfs(under, it, child)                          # add the height             under[child] += under[it]              # Function to return the DFS of subtree of node def printDFSofSubtree(node, under):         # index of node in the original DFS     ind = mp[node]          # height of subtree of node     height = under[node]         print("The DFS of subtree", node, ":", end=" ")         # print the DFS of subtree     for i in range(ind,ind + under[node]):        print(a[i], end=" ")     print()     # Function to add edges to a tree def addEdge(x, y):    v[x].append(y)     v[y].append(x) Â
# Marks the index of node in original DFS def markIndexDfs():         size = len(a)         # marks the index     for i in range(size):        mp[a[i]] = i      # Driver Code Â
n = 7Â
# add edges of a tree addEdge(1, 2) addEdge(1, 3) addEdge(2, 4) addEdge(2, 5) addEdge(4, 6) addEdge(4, 7) Â
# array to store the height of subtree # of every node in a tree under = [0]*(n + 1)Â
# Call the function DFS to generate the DFS dfs(under, 1, 0) Â
# Function call to mark the index of node markIndexDfs() Â
# Query 1 printDFSofSubtree(2, under)Â
# Query 2 printDFSofSubtree(4, under)Â
# This code is contributed by SHUBHAMSINGH10 |
C#
// C# program for queries for DFS// of subtree of a node in a treeusing System;using System.Collections.Generic;class GFG{Â Â Â Â Â static int N = 100000;Â
// Adjacency list to // store the tree nodes // connectionstatic List<int> []v = Â Â Â Â Â Â Â new List<int>[N];Â
// Stores the index of node in DFSstatic Dictionary<int,                  int> mp = new Dictionary<int,                                           int>();Â
// Stores the index of node in// original nodestatic List<int> a = new List<int>();Â
// Function to call DFS and // count nodes under that // subtreestatic void dfs(int []under,                 int child,                int parent){     // Stores the DFS of tree  a.Add(child);Â
  // Height of subtree  under[child] = 1;Â
  // Iterate for children  foreach(int it in v[child])  {    // If not equal to parent     // so that it does not     // traverse back    if (it != parent)     {      // Call DFS for subtree      dfs(under, it, child);Â
      // Add the height      under[child] += under[it];    }  }}Â
// Function to print the DFS of // subtree of nodestatic void printDFSofSubtree(int node,                              int []under){     // Index of node in the   // original DFS  int ind = mp[node];Â
  // Height of subtree of node  int height = under[node];Â
  Console.Write("The DFS of subtree " +                  node + ": ");Â
  // Print the DFS of subtree  for(int i = ind;           i < ind + under[node]; i++)  {    Console.Write(a[i] + " ");  }  Console.WriteLine();}Â
// Function to add edges// to a treestatic void addEdge(int x, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int y){Â Â v[x].Add(y);Â Â v[y].Add(x);}Â
// Marks the index of node // in original DFSstatic void markIndexDfs(){Â Â int size = a.Count;Â
  // Marks the index  for(int i = 0; i < size; i++)   {    mp.Add(a[i], i);  }}Â
// Driver Codepublic static void Main(String[] args){Â Â int n = 7;Â
  for(int i = 0; i < v.Length; i++)    v[i] = new List<int>();Â
  // Add edges of a tree  addEdge(1, 2);  addEdge(1, 3);  addEdge(2, 4);  addEdge(2, 5);  addEdge(4, 6);  addEdge(4, 7);Â
  // Array to store the height   // of subtree of every node   // in a tree  int []under = new int[n + 1];Â
  // Call the function DFS to  // generate the DFS  dfs(under, 1, 0);Â
  // Function call to mark the  // index of node  markIndexDfs();Â
  // Query 1  printDFSofSubtree(2, under);Â
  // Query 1  printDFSofSubtree(4, under);}}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â
// Javascript program for queries for DFS// of subtree of a node in a treevar N = 100000;Â
// Adjacency list to // store the tree nodes // connectionvar v = Array.from(Array(N), () => Array());Â
// Stores the index of node in DFSvar mp = new Map();Â
// Stores the index of node in// original nodevar a = [];Â
// Function to call DFS and // count nodes under that // subtreefunction dfs(under, child, parent){          // Stores the DFS of tree    a.push(child);         // Height of subtree    under[child] = 1;         // Iterate for children    for(var it of v[child])    {                 // If not equal to parent         // so that it does not         // traverse back        if (it != parent)         {                         // Call DFS for subtree            dfs(under, it, child);                         // push the height            under[child] += under[it];        }    }}Â
// Function to print the DFS of // subtree of nodefunction printDFSofSubtree(node, under){          // Index of node in the     // original DFS    var ind = mp.get(node);         // Height of subtree of node    var height = under[node];         document.write("The DFS of subtree " +                    node + ": ");         // Print the DFS of subtree    for(var i = ind;             i < ind + under[node]; i++)    {        document.write(a[i] + " ");    }    document.write("<br>");}Â
// Function to add edges// to a treefunction addEdge(x, y){Â Â Â Â v[x].push(y);Â Â Â Â v[y].push(x);}Â
// Marks the index of node // in original DFSfunction markIndexDfs(){    var size = a.length;         // Marks the index    for(var i = 0; i < size; i++)     {        mp.set(a[i], i);    }}Â
// Driver Codevar n = 7;for(var i = 0; i < v.length; i++)Â Â Â Â v[i] = Array();Â Â Â Â Â // push edges of a treeaddEdge(1, 2);addEdge(1, 3);addEdge(2, 4);addEdge(2, 5);addEdge(4, 6);addEdge(4, 7);Â
// Array to store the height // of subtree of every node // in a treevar under = Array(n + 1);Â
// Call the function DFS to// generate the DFSdfs(under, 1, 0);Â
// Function call to mark the// index of nodemarkIndexDfs();Â
// Query 1printDFSofSubtree(2, under);Â
// Query 1printDFSofSubtree(4, under);Â
// This code is contributed by rutvik_56Â
</script> |
The DFS of subtree 2: 2 4 6 7 5 The DFS of subtree 4: 4 6 7
Â
Time Complexity: O( N + M ), where N is the number of nodes and M is the number of edges for pre-calculation, and O(N) for queries in the worst case.Â
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

