📜  查询树中子树的 DFS

📅  最后修改于: 2022-05-13 01:57:20.092000             🧑  作者: Mango

查询树中子树的 DFS

给定一棵有 N 个节点和 N-1 条边的树。任务是为多个查询打印给定节点的子树的 DFS。 DFS 必须包含给定节点作为子树的根。

在上面的树中,如果给定 1 作为节点,那么子树的 DFS 将为1 2 4 6 7 5 3
如果给定 2 作为节点,那么子树的 DFS 将为2 4 6 7 5. .

方法:

  • 在邻接列表中添加节点之间的边。
  • 调用 DFS函数生成完整树的 DFS。
  • 使用 under[] 数组存储给定节点下的子树的高度,包括该节点。
  • 在 DFS函数中,在每次递归调用时不断增加子树的大小。
  • 使用散列标记完成的 DFS 中的节点索引。
  • 节点的子树的 DFS 将始终是从节点(比如索引 ind )到(ind+height of subtree)的连续子数组。
  • 获取已使用散列存储的节点的索引,并从原始 DFS 打印节点,直到 index = ind + 已存储在 under[node] 中的子树的高度。

下面是上述方法的实现。

C++
// C++ program for Queries
// for DFS of subtree of a node in a tree
#include 
using namespace std;
const int N = 100000;
 
// Adjacency list to store the
// tree nodes connection
vector v[N];
 
// stores the index of node in DFS
unordered_map mp;
 
// stores the index of node in
// original node
vector a;
 
// Function to call DFS and count nodes
// under that subtree
void 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 node
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];
 
    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 tree
void addEdge(int x, int y)
{
    v[x].push_back(y);
    v[y].push_back(x);
}
 
// Marks the index of node in original DFS
void markIndexDfs()
{
    int size = a.size();
 
    // marks the index
    for (int i = 0; i < size; i++) {
        mp[a[i]] = i;
    }
}
 
// Driver Code
int 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 tree
import java.util.*;
 
class GFG{
     
static int N = 100000;
 
// Adjacency list to store the
// tree nodes connection
@SuppressWarnings("unchecked")
static Vector []v = new Vector[N];
 
// Stores the index of node in DFS
static HashMap mp = new HashMap();
 
// Stores the index of node in
// original node
static Vector a = new Vector<>();
 
// Function to call DFS and count nodes
// under that subtree
static 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 node
static 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 tree
static void addEdge(int x, int y)
{
    v[x].add(y);
    v[y].add(x);
}
 
// Marks the index of node in original DFS
static void markIndexDfs()
{
    int size = a.size();
 
    // Marks the index
    for(int i = 0; i < size; i++)
    {
        mp.put(a.get(i), i);
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 7;
     
    for(int i = 0; i < v.length; i++)
        v[i] = new Vector();
         
    // 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 tree
using System;
using System.Collections.Generic;
class GFG{
     
static int N = 100000;
 
// Adjacency list to
// store the tree nodes
// connection
static List []v =
       new List[N];
 
// Stores the index of node in DFS
static Dictionary mp = new Dictionary();
 
// Stores the index of node in
// original node
static List a = new List();
 
// Function to call DFS and
// count nodes under that
// subtree
static 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 node
static 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 tree
static void addEdge(int x,
                    int y)
{
  v[x].Add(y);
  v[y].Add(x);
}
 
// Marks the index of node
// in original DFS
static void markIndexDfs()
{
  int size = a.Count;
 
  // Marks the index
  for(int i = 0; i < size; i++)
  {
    mp.Add(a[i], i);
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  int n = 7;
 
  for(int i = 0; i < v.Length; i++)
    v[i] = new List();
 
  // 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


输出:
The DFS of subtree 2: 2 4 6 7 5 
The DFS of subtree 4: 4 6 7

时间复杂度: O(N + M),其中 N 是节点数,M 是用于预计算的边数,O(N) 用于最坏情况下的查询。
辅助空间: O(N)