The Wayback Machine - https://web.archive.org/web/20210209153827/https://www.geeksforgeeks.org/print-all-nodes-present-in-the-subtree-of-a-given-node-of-a-binary-tree/
Skip to content
Related Articles

Related Articles

Print all nodes present in the subtree of a given node of a Binary Tree
  • Last Updated : 08 Feb, 2021

Given two arrays Node_ID[] and Parent_ID[]., construct a binary tree where value of ith node is equal to Node_ID[i] and parent of ith node is Parent_ID[i]. Given a node X, the task is to print node values of the tree rooted at X.

Examples:

Input: Node_ID[]= [11, 48, 100, 5], Parent_ID[] = [48, 0, 5, 48], X = 5
Output: [5, 100]
Explanation:
The tree constructed is as follows:
   48
 /     \
11     5
       /
    100
Therefore, subtree of the node 5 contains the nodes {5, 100}.

Input: Node_ID[] = [1, 2, 3], Parent_ID[] = [0, 1, 1], X = 2
Output: [2]

Naive Approach: Follow the steps below to solve the problem



  1. Construct a tree structure from Node_ID[] and Parent_ID[]
  2. Store the nodes with parent X in vector tree
  3. For each node, check if X is an ancestor of that node
  4. If found to be true, store the node in vector tree. Otherwise, continue.
  5. Print the nodes present in vector tree

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
// Function to print nodes
// in the tree rooted at x
void subtreeX(vector<int>& nid,
              vector<int>& pid, int x)
{
    unordered_map<int, int> parent;
  
    vector<int> 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<int> nid = { 11, 48, 100, 5 };
    vector<int> 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;
}

chevron_right


Output:

5 100

Time Complexity: O(N2) 
Auxiliary Space: O(N) 
 

Efficient Approach : Follow the steps below to optimize the above approach:

  1. Construct a tree structure from Node_ID[] and Parent_ID[]
  2. Perform DFS from node X.
  3. Store the nodes in a vector tree
  4. Print the nodes present in the vector tree

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
// DFS to traverse subtree rooted  at x
void dfs(int x, vector<int>& tree,
         map<int, vector<int> >& 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<int>& nid,
              vector<int>& pid, int x)
{
    int n = nid.size();
    map<int, vector<int> > 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<int>();
        }
  
        child[pid[i]].push_back(nid[i]);
    }
  
    // Stores nodes in the subtree
    vector<int> tree;
  
    // Perform DFS from node x
    dfs(x, tree, child);
  
    for (int node : tree) {
        cout << node << " ";
    }
}
  
// Driver Code
int main()
{
    vector<int> nid = { 11, 48, 100, 5 };
    vector<int> 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;
}

chevron_right


Output:

5 100

Time Complexity: O(N) 
Auxiliary Space: O(N) 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :