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:
- Find the parent of a node in the given binary tree
- Find the path from root to the given nodes of a tree for multiple queries
- Find distance of nodes from root in a tree for multiple queries
- Check whether a node is leaf node or not for multiple queries
- Find the winner of the match | Multiple Queries
- Find right sibling of a binary tree with parent pointers
- Find Height of Binary Tree represented by Parent array
- Queries to find distance between two nodes of a Binary tree
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Sum of all the parent nodes having child node x
- Find mirror of a given node in Binary tree
- Find root of the tree where children id sum for every node is given
- Find the Deepest Node in a Binary Tree
- Find the Kth node in the DFS traversal of a given subtree in a 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.