Given a tree and a node, the task is to find the parent of the given node in the tree. Print -1 if the given node is the root node.
Input: Node = 3 1 / \ 2 3 / \ 4 5 Output: 1 Input: Node = 1 1 / \ 2 3 / \ 4 5 / 6 Output: -1
Approach: Write a recursive function that takes the current node and its parent as the arguments (root node is passed with -1 as its parent). If the current node is equal to the required node then print its parent and return else call the function recursively for its children and the current node as the parent.
Below is the implementation of the 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.
- Find parent of given node in a Binary Tree with given postorder traversal
- Find parent of each node in a tree for multiple queries
- Find Height of Binary Tree represented by Parent array
- Find right sibling of a binary tree with parent pointers
- Construct Binary Tree from given Parent Array representation
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Maximum parent children sum in Binary tree
- Sum of all parent-child differences in a Binary Tree
- Sum of all the child nodes with even parent values in a Binary Tree
- Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
- Height of n-ary tree if parent array is given
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Identify all Grand-Parent Nodes of each Node in a Map
- Sum of all the parent nodes having child node x
- Ways to color a skewed tree such that parent and child have different colors
- Height of a generic tree from parent array
- Check whether a given binary tree is skewed binary tree or not?
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Find distance from root to given 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.