Find parent of each node in a tree for multiple queries
Given a tree with N vertices numbered from 0 to N – 1 and Q query containing nodes in the tree, the task is to find the parent node of the given node for multiple queries. Consider the 0th node as the root node and take the parent of the root node as the root itself.
Examples:
Tree:
0
/ \
1 2
| / \
3 4 5
Input: N = 2
Output: 0
Explanation:
Parent of node 2 is node 0 i.e root node
Input: N = 3
Output: 1
Explanation:
Parent of node 3 is node 1
Approach:
By default, we assign the parent of the root node as the root itself. Then, we traverse the tree using Breadth First Traversal(BFS). When we mark the children of node s as visited, we also assign the parent node of these children as the node s. Finally, for different queries, the value of the parent[] of the node is printed.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int sz = 1e5;
vector< int > tree[sz + 1];
bool vis[sz + 1];
int ans[sz + 1];
void addEdge( int a, int b)
{
tree[a].push_back(b);
tree[b].push_back(a);
}
void bfs( int node)
{
queue<pair< int , int > > qu;
qu.push({ node, 0 });
while (!qu.empty()) {
pair< int , int > p = qu.front();
qu.pop();
ans[p.first] = p.second;
vis[p.first] = true ;
for ( int child : tree[p.first]) {
if (!vis[child]) {
qu.push({ child, p.first });
}
}
}
}
int main()
{
int n = 6;
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(2, 5);
bfs(0);
int q[] = { 2, 3 };
for ( int i = 0; i < 2; i++) {
cout << ans[q[i]] << '\n' ;
}
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int sz = ( int ) 1e5;
static Vector<Integer> []tree = new Vector[sz + 1 ];
static boolean []vis = new boolean [sz + 1 ];
static int []ans = new int [sz + 1 ];
static class pair
{
int first, second;
public pair( int first, int second)
{
this .first = first;
this .second = second;
}
}
static void addEdge( int a, int b)
{
tree[a].add(b);
tree[b].add(a);
}
static void bfs( int node)
{
Queue<pair> qu = new LinkedList<>();
qu.add( new pair(node, 0 ));
while (!qu.isEmpty())
{
pair p = qu.peek();
qu.remove();
ans[p.first] = p.second;
vis[p.first] = true ;
for ( int child : tree[p.first])
{
if (!vis[child])
{
qu.add( new pair(child, p.first ));
}
}
}
}
public static void main(String[] args)
{
int n = 6 ;
for ( int i = 0 ; i < sz + 1 ; i++)
tree[i] = new Vector<Integer>();
addEdge( 0 , 1 );
addEdge( 0 , 2 );
addEdge( 1 , 3 );
addEdge( 2 , 4 );
addEdge( 2 , 5 );
bfs( 0 );
int q[] = { 2 , 3 };
for ( int i = 0 ; i < 2 ; i++)
{
System.out.println(ans[q[i]]);
}
}
}
|
Python3
sz = 10 * * 5
tree = [[] for _ in range (sz + 1 )]
vis = [ 0 ] * (sz + 1 )
ans = [ 0 ] * (sz + 1 )
def addEdge(a, b):
tree[a].append(b)
tree[b].append(a)
def bfs(node):
qu = []
qu.append([node, 0 ])
while ( len (qu)):
p = qu[ 0 ]
qu.pop( 0 )
ans[p[ 0 ]] = p[ 1 ]
vis[p[ 0 ]] = True
for child in tree[p[ 0 ]]:
if ( not vis[child]):
qu.append([child, p[ 0 ]])
n = 6
addEdge( 0 , 1 )
addEdge( 0 , 2 )
addEdge( 1 , 3 )
addEdge( 2 , 4 )
addEdge( 2 , 5 )
bfs( 0 )
q = [ 2 , 3 ]
for i in range ( 2 ):
print (ans[q[i]])
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int sz = ( int ) 1e5;
static List< int > []tree = new List< int >[sz + 1];
static Boolean []vis = new Boolean[sz + 1];
static int []ans = new int [sz + 1];
public class pair
{
public int first, second;
public pair( int first, int second)
{
this .first = first;
this .second = second;
}
}
static void addEdge( int a, int b)
{
tree[a].Add(b);
tree[b].Add(a);
}
static void bfs( int node)
{
Queue<pair> qu = new Queue<pair>();
qu.Enqueue( new pair(node, 0 ));
while (qu.Count != 0)
{
pair p = qu.Peek();
qu.Dequeue();
ans[p.first] = p.second;
vis[p.first] = true ;
foreach ( int child in tree[p.first])
{
if (!vis[child])
{
qu.Enqueue( new pair(child, p.first ));
}
}
}
}
public static void Main(String[] args)
{
for ( int i = 0; i < sz + 1; i++)
tree[i] = new List< int >();
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(2, 5);
bfs(0);
int []q = { 2, 3 };
for ( int i = 0; i < 2; i++)
{
Console.WriteLine(ans[q[i]]);
}
}
}
|
Javascript
<script>
let sz = 1e5;
let tree = new Array(sz + 1);
let vis = new Array(sz + 1);
vis.fill( false );
let ans = new Array(sz + 1);
ans.fill(0);
function addEdge(a, b)
{
tree[a].push(b);
tree[b].push(a);
}
function bfs(node)
{
let qu = [];
qu.push([node, 0 ]);
while (qu.length > 0)
{
let p = qu[0];
qu.shift();
ans[p[0]] = p[1];
vis[p[0]] = true ;
for (let child = 0; child < tree[p[0]].length; child++)
{
if (!vis[tree[p[0]][child]])
{
qu.push([tree[p[0]][child], p[0]]);
}
}
}
}
let n = 6;
for (let i = 0; i < sz + 1; i++)
tree[i] = [];
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(2, 5);
bfs(0);
let q = [ 2, 3 ];
for (let i = 0; i < 2; i++)
{
document.write(ans[q[i]] + "</br>" );
}
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
20 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...