📌  相关文章
📜  打印二叉树给定节点的子树中存在的所有节点

📅  最后修改于: 2021-09-03 03:20:33             🧑  作者: Mango

给定两个数组Node_ID[]Parent_ID[]。 , 构造一个二叉树,其中i节点的值等于Node_ID[i]并且i节点的父节点是Parent_ID[i] 。给定一个节点X ,任务是打印以X为根的树的节点值。

例子

朴素的方法:按照以下步骤解决问题

  1. Node_ID[]Parent_ID[]构建树结构
  2. 将具有父 X 的节点存储在向量树中
  3. 对于每个节点,检查X是否是该节点的祖先
  4. 如果发现为真,则将该节点存储在向量树中。否则,继续。
  5. 打印向量树中存在的节点

下面是上述方法的实现:

C++
#include 
using namespace std;
 
// Function to print nodes
// in the tree rooted at x
void subtreeX(vector& nid,
              vector& pid, int x)
{
    unordered_map parent;
 
    vector tree;
 
    // Map every node to its parent
    for (int i = 0; i < nid.size(); i++) {
        parent[nid[i]] = pid[i];
    }
 
    // Subtree with x as root
    tree.push_back(x);
 
    for (int i = 0; i < nid.size(); i++) {
        int k = nid[i];
        int p = k;
 
        // Iterate until k becomes
        // equal to the root
        while (k != 0) {
 
            if (parent[k] == x) {
 
                // x is an ancestor of nid[i]
                tree.push_back(nid[i]);
                break;
            }
 
            k = parent[k];
        }
    }
 
    // Print elements in the subtree
    for (int node : tree)
        cout << node << " ";
}
 
// Driver Code
int main()
{
    vector nid = { 11, 48, 100, 5 };
    vector pid = { 48, 0, 5, 48 };
    int x = 5;
 
    // Function call to print nodes
    // in the tree rooted at x
    subtreeX(nid, pid, x);
 
    return 0;
}


Java
import java.util.*;
class GFG
{
 
    // Function to print nodes
    // in the tree rooted at x
    static void subtreeX(int[] nid, int[] pid, int x)
    {
        HashMap parent
        = new HashMap();
 
        List tree = new LinkedList<>();
 
        // Map every node to its parent
        for (int i = 0; i < nid.length; i++)
        {
            parent.put(nid[i], pid[i]);
        }
 
        // Subtree with x as root
        tree.add(x);
        for (int i = 0; i < nid.length; i++)
        {
            int k = nid[i];
            int p = k;
 
            // Iterate until k becomes
            // equal to the root
            while (k != 0)
            {
                 
                if (parent.containsKey(k) && parent.get(k) == x)
                {
                   
                    // x is an ancestor of nid[i]
                    tree.add(nid[i]);
                    break;
                }
                k = parent.containsKey(k) ? parent.get(k) : -1;
            }
        }
 
        // Print elements in the subtree
        for (int node : tree)
            System.out.print(node + " ");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] nid = { 11, 48, 100, 5 };
        int[] pid = { 48, 0, 5, 48 };
        int x = 5;
 
        // Function call to print nodes
        // in the tree rooted at x
        subtreeX(nid, pid, x);
    }
}
 
// This code is contributed by 29AjayKumar


Python3
# Function to prnodes
# in the tree rooted at x
def subtreeX(nid, pid, x):
    parent = {}
    tree = []
 
    # Map every node to its parent
    for i in range(len(nid)):
        parent[nid[i]] = pid[i]
 
    # Subtree with x as root
    tree.append(x)
    for i in range(len(nid)):
        k = nid[i]
        p = k
 
        # Iterate until k becomes
        # equal to the root
        while (k != 0):
            if (parent[k] == x):
 
                # x is an ancestor of nid[i]
                tree.append(nid[i])
                break
            k = parent[k]
 
    # Prelements in the subtree
    for node in tree:
        print(node, end = " ")
 
# Driver Code
if __name__ == '__main__':
    nid = [11, 48, 100, 5]
    pid = [48, 0, 5, 48 ]
    x = 5
 
    # Function call to prnodes
    # in the tree rooted at x
    subtreeX(nid, pid, x)
 
    # This code is contributed by mohit kumar 29.


C#
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Function to print nodes
  // in the tree rooted at x
  static void subtreeX(int[] nid, int[] pid, int x)
  {
    Dictionary parent
      = new Dictionary();
    List tree = new List();
 
    // Map every node to its parent
    for (int i = 0; i < nid.Length; i++)
    {
      parent.Add(nid[i], pid[i]);
    }
 
    // Subtree with x as root
    tree.Add(x);
    for (int i = 0; i < nid.Length; i++)
    {
      int k = nid[i];
      int p = k;
 
      // Iterate until k becomes
      // equal to the root
      while (k != 0)
      {      
        if (parent.ContainsKey(k) && parent[k] == x)
        {
 
          // x is an ancestor of nid[i]
          tree.Add(nid[i]);
          break;
        }
        k = parent.ContainsKey(k) ? parent[k] : -1;
      }
    }
 
    // Print elements in the subtree
    foreach (int node in tree)
      Console.Write(node + " ");
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int[] nid = { 11, 48, 100, 5 };
    int[] pid = { 48, 0, 5, 48 };
    int x = 5;
 
    // Function call to print nodes
    // in the tree rooted at x
    subtreeX(nid, pid, x);
  }
}
 
// This code is contributed by shikhasingrajput


C++
#include 
using namespace std;
 
// DFS to traverse subtree rooted  at x
void dfs(int x, vector& tree,
         map >& child)
{
    // Push x into the vector
    tree.push_back(x);
 
    // Check if x is a leaf node
    if (child.find(x) != child.end()) {
 
        // Recursively call dfs
        // for children of x
        for (int next : child[x]) {
            dfs(next, tree, child);
        }
    }
}
 
// Function to print nodes
// in the tree rooted at x
void SubtreeX(vector& nid,
              vector& pid, int x)
{
    int n = nid.size();
    map > child;
 
    // adding edges in a tree
    for (int i = 0; i < n; i++) {
 
        if (child.find(pid[i])
            == child.end()) {
 
            // Initialize adjacency list
            child[pid[i]] = vector();
        }
 
        child[pid[i]].push_back(nid[i]);
    }
 
    // Stores nodes in the subtree
    vector tree;
 
    // Perform DFS from node x
    dfs(x, tree, child);
 
    for (int node : tree) {
        cout << node << " ";
    }
}
 
// Driver Code
int main()
{
    vector nid = { 11, 48, 100, 5 };
    vector pid = { 48, 0, 5, 48 };
    int x = 5;
 
    // Function call to print nodes
    // in the tree rooted at x
    SubtreeX(nid, pid, x);
 
    return 0;
}


Java
import java.io.*;
import java.util.*;
 
class GFG{
     
// DFS to traverse subtree rooted  at x
static void dfs(int x, Vector tree,
          Map> child)
{
     
    // Push x into the vector
    tree.add(x);
  
    // Check if x is a leaf node
    if (child.containsKey(x))
    {
         
        // Recursively call dfs
        // for children of x
        for(int next : child.get(x))
        {
            dfs(next, tree, child);
        }
    }
}
  
// Function to print nodes
// in the tree rooted at x
static void SubtreeX(Vector nid,
                     Vector pid, int x)
{
    int n = nid.size();
    Map> child = new HashMap<>();
  
    // Adding edges in a tree
    for(int i = 0; i < n; i++)
    {
        if (!child.containsKey(pid.get(i)))
        {
             
            // Initialize adjacency list
            child.put(pid.get(i), new Vector());
        }
        child.get(pid.get(i)).add(nid.get(i));
    }
  
    // Stores nodes in the subtree
    Vector tree = new Vector();
  
    // Perform DFS from node x
    dfs(x, tree, child);
  
    for(int node : tree)
    {
        System.out.print(node + " ");
    }
}
  
// Driver Code
public static void main (String[] args)
{
    Vector nid = new Vector(
        Arrays.asList(11, 48, 100, 5));
    Vector pid = new Vector(
        Arrays.asList(48, 0, 5, 48));
     
    int x = 5;
 
    // Function call to print nodes
    // in the tree rooted at x
    SubtreeX(nid, pid, x);
}
}
 
// This code is contributed by rag2127


Python3
# DFS to traverse subtree rooted  at x
def dfs(x, tree, child):
   
    # Push x into the vector
    tree.append(x)
     
    # Check if x is a leaf node
    if x in child:
       
        # Recursively call dfs
        # for children of x
        for nextt in child[x]:
            dfs(nextt, tree, child)
 
# Function to print nodes
# in the tree rooted at x
def SubtreeX(nid,pid,x):
    n = len(nid)
    child = {}
     
    #  Adding edges in a tree  
    for i in range(n):
        if pid[i] not in child:
           
            # Initialize adjacency list
            child[pid[i]] = []
        child[pid[i]].append(nid[i])
     
    # Stores nodes in the subtree
    tree = []
     
    # Perform DFS from node x
    dfs(x, tree, child)
    print(*tree)
     
# Driver Code
nid = [11, 48, 100, 5]
pid = [48, 0, 5, 48]
x = 5
 
# Function call to print nodes
# in the tree rooted at x
SubtreeX(nid, pid, x)
 
# This code is contributed by avanitrachhadiya2155


输出:
5 100

时间复杂度:O(N 2 )
辅助空间:O(N)

高效方法:按照以下步骤优化上述方法:

  1. Node_ID[]Parent_ID[]构建树结构
  2. 从节点X执行 DFS。
  3. 将节点存储在向量树中
  4. 打印向量树中存在的节点

下面是上述方法的实现:

C++

#include 
using namespace std;
 
// DFS to traverse subtree rooted  at x
void dfs(int x, vector& tree,
         map >& child)
{
    // Push x into the vector
    tree.push_back(x);
 
    // Check if x is a leaf node
    if (child.find(x) != child.end()) {
 
        // Recursively call dfs
        // for children of x
        for (int next : child[x]) {
            dfs(next, tree, child);
        }
    }
}
 
// Function to print nodes
// in the tree rooted at x
void SubtreeX(vector& nid,
              vector& pid, int x)
{
    int n = nid.size();
    map > child;
 
    // adding edges in a tree
    for (int i = 0; i < n; i++) {
 
        if (child.find(pid[i])
            == child.end()) {
 
            // Initialize adjacency list
            child[pid[i]] = vector();
        }
 
        child[pid[i]].push_back(nid[i]);
    }
 
    // Stores nodes in the subtree
    vector tree;
 
    // Perform DFS from node x
    dfs(x, tree, child);
 
    for (int node : tree) {
        cout << node << " ";
    }
}
 
// Driver Code
int main()
{
    vector nid = { 11, 48, 100, 5 };
    vector pid = { 48, 0, 5, 48 };
    int x = 5;
 
    // Function call to print nodes
    // in the tree rooted at x
    SubtreeX(nid, pid, x);
 
    return 0;
}

Java

import java.io.*;
import java.util.*;
 
class GFG{
     
// DFS to traverse subtree rooted  at x
static void dfs(int x, Vector tree,
          Map> child)
{
     
    // Push x into the vector
    tree.add(x);
  
    // Check if x is a leaf node
    if (child.containsKey(x))
    {
         
        // Recursively call dfs
        // for children of x
        for(int next : child.get(x))
        {
            dfs(next, tree, child);
        }
    }
}
  
// Function to print nodes
// in the tree rooted at x
static void SubtreeX(Vector nid,
                     Vector pid, int x)
{
    int n = nid.size();
    Map> child = new HashMap<>();
  
    // Adding edges in a tree
    for(int i = 0; i < n; i++)
    {
        if (!child.containsKey(pid.get(i)))
        {
             
            // Initialize adjacency list
            child.put(pid.get(i), new Vector());
        }
        child.get(pid.get(i)).add(nid.get(i));
    }
  
    // Stores nodes in the subtree
    Vector tree = new Vector();
  
    // Perform DFS from node x
    dfs(x, tree, child);
  
    for(int node : tree)
    {
        System.out.print(node + " ");
    }
}
  
// Driver Code
public static void main (String[] args)
{
    Vector nid = new Vector(
        Arrays.asList(11, 48, 100, 5));
    Vector pid = new Vector(
        Arrays.asList(48, 0, 5, 48));
     
    int x = 5;
 
    // Function call to print nodes
    // in the tree rooted at x
    SubtreeX(nid, pid, x);
}
}
 
// This code is contributed by rag2127

蟒蛇3

# DFS to traverse subtree rooted  at x
def dfs(x, tree, child):
   
    # Push x into the vector
    tree.append(x)
     
    # Check if x is a leaf node
    if x in child:
       
        # Recursively call dfs
        # for children of x
        for nextt in child[x]:
            dfs(nextt, tree, child)
 
# Function to print nodes
# in the tree rooted at x
def SubtreeX(nid,pid,x):
    n = len(nid)
    child = {}
     
    #  Adding edges in a tree  
    for i in range(n):
        if pid[i] not in child:
           
            # Initialize adjacency list
            child[pid[i]] = []
        child[pid[i]].append(nid[i])
     
    # Stores nodes in the subtree
    tree = []
     
    # Perform DFS from node x
    dfs(x, tree, child)
    print(*tree)
     
# Driver Code
nid = [11, 48, 100, 5]
pid = [48, 0, 5, 48]
x = 5
 
# Function call to print nodes
# in the tree rooted at x
SubtreeX(nid, pid, x)
 
# This code is contributed by avanitrachhadiya2155
输出:
5 100

时间复杂度:O(N)
辅助空间:O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live