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;
// 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;
}
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<Integer, Integer> parent
= new HashMap<Integer, Integer>();
List<Integer> 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 print nodes
# 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]
# Print elements 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 print nodes
# 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<int, int> parent
= new Dictionary<int, int>();
List<int> tree = new List<int>();
// 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
JavaScript
<script>
// Function to print nodes
// in the tree rooted at x
function subtreeX(nid, pid, x)
{
var parent = new Map();
var tree = [];
// Map every node to its parent
for (var i = 0; i < nid.length; i++)
{
parent.set(nid[i], pid[i]);
}
// Subtree with x as root
tree.push(x);
for (var i = 0; i < nid.length; i++)
{
var k = nid[i];
var p = k;
// Iterate until k becomes
// equal to the root
while (k != 0)
{
if (parent.has(k) && parent.get(k) == x)
{
// x is an ancestor of nid[i]
tree.push(nid[i]);
break;
}
k = parent.has(k) ? parent.get(k) : -1;
}
}
// Print elements in the subtree
for(var node of tree)
document.write(node + " ");
}
// Driver Code
var nid = [11, 48, 100, 5];
var pid = [48, 0, 5, 48];
var x = 5;
// Function call to print nodes
// in the tree rooted at x
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;
// 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;
}
Java
import java.io.*;
import java.util.*;
class GFG{
// DFS to traverse subtree rooted at x
static void dfs(int x, Vector<Integer> tree,
Map<Integer, Vector<Integer>> 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<Integer> nid,
Vector<Integer> pid, int x)
{
int n = nid.size();
Map<Integer, Vector<Integer>> 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<Integer>());
}
child.get(pid.get(i)).add(nid.get(i));
}
// Stores nodes in the subtree
Vector<Integer> tree = new Vector<Integer>();
// 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<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;
// 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
C#
using System;
using System.Collections.Generic;
class GFG {
// DFS to traverse subtree rooted at x
static void dfs(int x, List<int> tree,
Dictionary<int, List<int>> 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
foreach(int next in child[x])
{
dfs(next, tree, child);
}
}
}
// Function to print nodes
// in the tree rooted at x
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>>();
// Adding edges in a tree
for(int i = 0; i < n; i++)
{
if (!child.ContainsKey(pid[i]))
{
// Initialize adjacency list
child[pid[i]] = new List<int>();
}
child[pid[i]].Add(nid[i]);
}
// Stores nodes in the subtree
List<int> tree = new List<int>();
// Perform DFS from node x
dfs(x, tree, child);
foreach(int node in tree)
{
Console.Write(node + " ");
}
}
// Driver code
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;
// Function call to print nodes
// in the tree rooted at x
SubtreeX(nid, pid, x);
}
}
// This code is contributed by decode2207.
JavaScript
<script>
// DFS to traverse subtree rooted at x
function dfs(x,tree,child)
{
// Push x into the vector
tree.push(x);
// Check if x is a leaf node
if (child.has(x))
{
// Recursively call dfs
// for children of x
for(let next=0;next< child.get(x).length;next++)
{
dfs(child.get(x)[next], tree, child);
}
}
}
// Function to print nodes
// in the tree rooted at x
function SubtreeX(nid,pid,x)
{
let n = nid.length;
let child = new Map();
// Adding edges in a tree
for(let i = 0; i < n; i++)
{
if (!child.has(pid[i]))
{
// Initialize adjacency list
child.set(pid[i], []);
}
child.get(pid[i]).push(nid[i]);
}
// Stores nodes in the subtree
let tree = [];
// Perform DFS from node x
dfs(x, tree, child);
for(let node=0;node< tree.length;node++)
{
document.write(tree[node] + " ");
}
}
// Driver Code
let nid = [11, 48, 100, 5];
let pid = [48, 0, 5, 48];
let x = 5;
// Function call to print nodes
// in the tree rooted at x
SubtreeX(nid, pid, x);
// This code is contributed by unknown2108
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Print all nodes except rightmost node of every level of the Binary Tree
Given a binary tree, the task is to print all the nodes except the rightmost in every level of the tree. The root is considered at level 0, and rightmost node of any level is considered as a node at position 0.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 2 4 5 7 9 Input: 1 / \ 2 3
7 min read
Find sum of all nodes of the given perfect binary tree
Given a positive integer L which represents the number of levels in a perfect binary tree. Given that the leaf nodes in this perfect binary tree are numbered starting from 1 to n, where n is the number of leaf nodes. And the parent node is the sum of the two child nodes. Our task is to write a progr
11 min read
Print the number of set bits in each node of a Binary Tree
Given a Binary Tree. The task is to print the number of set bits in each of the nodes in the Binary Tree. The idea is to traverse the given binary tree using any tree traversal method, and for each node calculate the number of set bits and print it. Note: One can also use the __builtin_popcount() fu
6 min read
Find the parent of a node in the given binary tree
Given a Binary Tree and a node, the task is to find the parent of the given node in the tree. Return -1 if the given node is the root node.Note: In a binary tree, a parent node of a given node is the node that is directly connected above the given node. Examples: Input: target = 3 Output: 1Explanati
6 min read
Print all Nodes of given Binary Tree at the Kth Level
Given a binary tree and an integer K, the task is to print all the integers at the Kth level in the tree from left to right. Examples: Input: Tree in the image below, K = 3 Output: 4 5 6Explanation: All the nodes present in level 3 of above binary tree from left to right are 4, 5, and 6. Input: Tree
5 min read
Sum of nodes in the left view of the given binary tree
Given a binary tree, the task is to find the sum of the nodes which are visible in the left view. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left.Examples: Example 1 : The Green colored nodes represents the left view in the below Binary tree. The Left
13 min read
Print the middle nodes of each level of a Binary Tree
Given a Binary Tree, the task is to print the middle nodes of each level of a binary tree. Considering M to be the number of nodes at any level, print (M/2)th node if M is odd. Otherwise, print (M/2)th node and ((M/2) + 1)th node. Examples: Input: Below is the given Tree: Output:12 35 1011 67 9Expla
11 min read
Print the nodes of binary tree as they become the leaf node
Given a binary tree. First print all leaf nodes, after that remove all the leaf nodes from the tree and now print all the new formed leaf nodes and keep doing this until all the nodes are removed from the tree. Examples :Â Input : 8 / \ 3 10 / \ / \ 1 6 14 4 / \ 7 13Output : 4 6 7 13 141 1038Source
10 min read
Print and remove leaf nodes of given Binary Tree on each iteration
Given a binary tree, the task is to: Print all the leaf nodes and then delete them all. Repeat this process till the tree becomes empty. Examples: Input: 1 /. \ 2 3 / \ 4 5 Output: Iteration 1: 4 5 3Iteration 2: 2Iteration 3: 1Explanation: The leaf nodes initially were 4, 5 and 3.When those were del
7 min read
Print all the nodes except the leftmost node in every level of the given binary tree
Given a binary tree, the task is to print all the nodes except the leftmost in every level of the tree. The root is considered at level 0, and left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 3 5 6 8 10 Input: 1 / \ 2
8 min read