# 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

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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:

Output:
0
1

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.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : 29AjayKumar, SHUBHAMSINGH10

Article Tags :