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.
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
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:
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 whether a node is leaf node or not for multiple queries
- Find parent of given node in a Binary Tree with given postorder traversal
- Find the parent of a node in the given binary tree
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Find distance of nodes from root in a tree for multiple queries
- Find the path from root to the given nodes of a tree for multiple queries
- Find farthest node from each node in Tree
- Find Height of Binary Tree represented by Parent array
- Find right sibling of a binary tree with parent pointers
- Level of Each node in a Tree from source node (using BFS)
- Farthest distance of a Node from each Node of a Tree
- Sum of all the parent nodes having child node x
- Find the winner of the match | Multiple Queries
- Find K-th smallest element in an array for multiple queries
- Construct Binary Tree from given Parent Array representation
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Height of n-ary tree if parent array is given
- Ways to color a skewed tree such that parent and child have different colors
- Maximum parent children sum in Binary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.