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:
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 parent of given node in a Binary Tree with given postorder traversal
- Find parent of each node in a tree for multiple queries
- Find right sibling of a binary tree with parent pointers
- Find Height of Binary Tree represented by Parent array
- Find mirror of a given node in Binary tree
- Find the Deepest Node in a Binary Tree
- Find the maximum node at a given level in a binary tree
- Find the color of given node in an infinite binary tree
- Find distance from root to given node in a binary tree
- Find n-th node in Preorder traversal of a Binary Tree
- Find the Deepest Node in a Binary Tree Using Queue STL - SET 2
- Find n-th node in Postorder traversal of a Binary Tree
- Find the node with minimum value in a Binary Search Tree
- Find the node with maximum value in a Binary Search Tree
- Find the node with maximum value in a Binary Search Tree using recursion
- Find the node with minimum value in a Binary Search Tree using recursion
- Find the kth node in vertical order traversal of a Binary Tree
- Maximum parent children sum in Binary tree
- Sum of all parent-child differences in a Binary Tree
- Construct Binary Tree from given Parent Array representation
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.