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:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find the parent of a node in the given binary tree
- Find parent of given node in a Binary Tree with given postorder traversal
- 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 GCD of each subtree of a given node in an N-ary Tree for Q queries
- Check whether a node is leaf node or not for multiple queries
- Find the winner of the match | Multiple Queries
- Find K-th smallest element in an array for multiple queries
- Find right sibling of a binary tree with parent pointers
- Find Height of Binary Tree represented by Parent array
- Find farthest node from each node in Tree
- Queries to find distance between two nodes of a Binary tree
- Find distance between two nodes in the given Binary tree for Q queries
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Sum of all the parent nodes having child node x
- Find mirror of a given node in Binary tree
- Find the maximum Even Digit Sum node in the given tree
- Find root of the tree where children id sum for every node is given
- Find the Deepest Node in a 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 firstname.lastname@example.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.