Print all nodes present in the subtree of a given node of a Binary Tree
Last Updated :
01 Feb, 2022
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
- Construct a tree structure from Node_ID[] and Parent_ID[]
- Store the nodes with parent X in vector tree
- For each node, check if X is an ancestor of that node
- If found to be true, store the node in vector tree. Otherwise, continue.
- Print the nodes present in vector tree
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void subtreeX(vector< int >& nid,
vector< int >& pid, int x)
{
unordered_map< int , int > parent;
vector< int > tree;
for ( int i = 0; i < nid.size(); i++) {
parent[nid[i]] = pid[i];
}
tree.push_back(x);
for ( int i = 0; i < nid.size(); i++) {
int k = nid[i];
int p = k;
while (k != 0) {
if (parent[k] == x) {
tree.push_back(nid[i]);
break ;
}
k = parent[k];
}
}
for ( int node : tree)
cout << node << " " ;
}
int main()
{
vector< int > nid = { 11, 48, 100, 5 };
vector< int > pid = { 48, 0, 5, 48 };
int x = 5;
subtreeX(nid, pid, x);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void subtreeX( int [] nid, int [] pid, int x)
{
HashMap<Integer, Integer> parent
= new HashMap<Integer, Integer>();
List<Integer> tree = new LinkedList<>();
for ( int i = 0 ; i < nid.length; i++)
{
parent.put(nid[i], pid[i]);
}
tree.add(x);
for ( int i = 0 ; i < nid.length; i++)
{
int k = nid[i];
int p = k;
while (k != 0 )
{
if (parent.containsKey(k) && parent.get(k) == x)
{
tree.add(nid[i]);
break ;
}
k = parent.containsKey(k) ? parent.get(k) : - 1 ;
}
}
for ( int node : tree)
System.out.print(node + " " );
}
public static void main(String[] args)
{
int [] nid = { 11 , 48 , 100 , 5 };
int [] pid = { 48 , 0 , 5 , 48 };
int x = 5 ;
subtreeX(nid, pid, x);
}
}
|
Python3
def subtreeX(nid, pid, x):
parent = {}
tree = []
for i in range ( len (nid)):
parent[nid[i]] = pid[i]
tree.append(x)
for i in range ( len (nid)):
k = nid[i]
p = k
while (k ! = 0 ):
if (parent[k] = = x):
tree.append(nid[i])
break
k = parent[k]
for node in tree:
print (node, end = " " )
if __name__ = = '__main__' :
nid = [ 11 , 48 , 100 , 5 ]
pid = [ 48 , 0 , 5 , 48 ]
x = 5
subtreeX(nid, pid, x)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static void subtreeX( int [] nid, int [] pid, int x)
{
Dictionary< int , int > parent
= new Dictionary< int , int >();
List< int > tree = new List< int >();
for ( int i = 0; i < nid.Length; i++)
{
parent.Add(nid[i], pid[i]);
}
tree.Add(x);
for ( int i = 0; i < nid.Length; i++)
{
int k = nid[i];
int p = k;
while (k != 0)
{
if (parent.ContainsKey(k) && parent[k] == x)
{
tree.Add(nid[i]);
break ;
}
k = parent.ContainsKey(k) ? parent[k] : -1;
}
}
foreach ( int node in tree)
Console.Write(node + " " );
}
public static void Main(String[] args)
{
int [] nid = { 11, 48, 100, 5 };
int [] pid = { 48, 0, 5, 48 };
int x = 5;
subtreeX(nid, pid, x);
}
}
|
Javascript
<script>
function subtreeX(nid, pid, x)
{
var parent = new Map();
var tree = [];
for ( var i = 0; i < nid.length; i++)
{
parent.set(nid[i], pid[i]);
}
tree.push(x);
for ( var i = 0; i < nid.length; i++)
{
var k = nid[i];
var p = k;
while (k != 0)
{
if (parent.has(k) && parent.get(k) == x)
{
tree.push(nid[i]);
break ;
}
k = parent.has(k) ? parent.get(k) : -1;
}
}
for ( var node of tree)
document.write(node + " " );
}
var nid = [11, 48, 100, 5];
var pid = [48, 0, 5, 48];
var x = 5;
subtreeX(nid, pid, x);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach : Follow the steps below to optimize the above approach:
- Construct a tree structure from Node_ID[] and Parent_ID[]
- Perform DFS from node X.
- Store the nodes in a vector tree
- Print the nodes present in the vector tree
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void dfs( int x, vector< int >& tree,
map< int , vector< int > >& child)
{
tree.push_back(x);
if (child.find(x) != child.end()) {
for ( int next : child[x]) {
dfs(next, tree, child);
}
}
}
void SubtreeX(vector< int >& nid,
vector< int >& pid, int x)
{
int n = nid.size();
map< int , vector< int > > child;
for ( int i = 0; i < n; i++) {
if (child.find(pid[i])
== child.end()) {
child[pid[i]] = vector< int >();
}
child[pid[i]].push_back(nid[i]);
}
vector< int > tree;
dfs(x, tree, child);
for ( int node : tree) {
cout << node << " " ;
}
}
int main()
{
vector< int > nid = { 11, 48, 100, 5 };
vector< int > pid = { 48, 0, 5, 48 };
int x = 5;
SubtreeX(nid, pid, x);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static void dfs( int x, Vector<Integer> tree,
Map<Integer, Vector<Integer>> child)
{
tree.add(x);
if (child.containsKey(x))
{
for ( int next : child.get(x))
{
dfs(next, tree, child);
}
}
}
static void SubtreeX(Vector<Integer> nid,
Vector<Integer> pid, int x)
{
int n = nid.size();
Map<Integer, Vector<Integer>> child = new HashMap<>();
for ( int i = 0 ; i < n; i++)
{
if (!child.containsKey(pid.get(i)))
{
child.put(pid.get(i), new Vector<Integer>());
}
child.get(pid.get(i)).add(nid.get(i));
}
Vector<Integer> tree = new Vector<Integer>();
dfs(x, tree, child);
for ( int node : tree)
{
System.out.print(node + " " );
}
}
public static void main (String[] args)
{
Vector<Integer> nid = new Vector<Integer>(
Arrays.asList( 11 , 48 , 100 , 5 ));
Vector<Integer> pid = new Vector<Integer>(
Arrays.asList( 48 , 0 , 5 , 48 ));
int x = 5 ;
SubtreeX(nid, pid, x);
}
}
|
Python3
def dfs(x, tree, child):
tree.append(x)
if x in child:
for nextt in child[x]:
dfs(nextt, tree, child)
def SubtreeX(nid,pid,x):
n = len (nid)
child = {}
for i in range (n):
if pid[i] not in child:
child[pid[i]] = []
child[pid[i]].append(nid[i])
tree = []
dfs(x, tree, child)
print ( * tree)
nid = [ 11 , 48 , 100 , 5 ]
pid = [ 48 , 0 , 5 , 48 ]
x = 5
SubtreeX(nid, pid, x)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void dfs( int x, List< int > tree,
Dictionary< int , List< int >> child)
{
tree.Add(x);
if (child.ContainsKey(x))
{
foreach ( int next in child[x])
{
dfs(next, tree, child);
}
}
}
static void SubtreeX(List< int > nid, List< int > pid, int x)
{
int n = nid.Count;
Dictionary< int , List< int >> child = new Dictionary< int , List< int >>();
for ( int i = 0; i < n; i++)
{
if (!child.ContainsKey(pid[i]))
{
child[pid[i]] = new List< int >();
}
child[pid[i]].Add(nid[i]);
}
List< int > tree = new List< int >();
dfs(x, tree, child);
foreach ( int node in tree)
{
Console.Write(node + " " );
}
}
static void Main() {
List< int > nid = new List< int >{11, 48, 100, 5};
List< int > pid = new List< int >{48, 0, 5, 48};
int x = 5;
SubtreeX(nid, pid, x);
}
}
|
Javascript
<script>
function dfs(x,tree,child)
{
tree.push(x);
if (child.has(x))
{
for (let next=0;next< child.get(x).length;next++)
{
dfs(child.get(x)[next], tree, child);
}
}
}
function SubtreeX(nid,pid,x)
{
let n = nid.length;
let child = new Map();
for (let i = 0; i < n; i++)
{
if (!child.has(pid[i]))
{
child.set(pid[i], []);
}
child.get(pid[i]).push(nid[i]);
}
let tree = [];
dfs(x, tree, child);
for (let node=0;node< tree.length;node++)
{
document.write(tree[node] + " " );
}
}
let nid = [11, 48, 100, 5];
let pid = [48, 0, 5, 48];
let x = 5;
SubtreeX(nid, pid, x);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...