Open In App

Find the parent of a node in the given binary tree

Last Updated : 13 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.
Examples: 

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: 
 

C++




// C++ implementation of the approach
#include <iostream>
using namespace std;
 
/* A binary tree node has data, pointer
to left child and a pointer
to right child */
struct Node {
    int data;
    struct Node *left, *right;
    Node(int data)
    {
        this->data = data;
        left = right = NULL;
    }
};
 
// Recursive function to find the
// parent of the given node
void findParent(struct Node* node,
                int val, int parent)
{
    if (node == NULL)
        return;
 
    // If current node is the required node
    if (node->data == val) {
 
        // Print its parent
        cout << parent;
    }
    else {
 
        // Recursive calls for the children
        // of the current node
        // Current node is now the new parent
        findParent(node->left, val, node->data);
        findParent(node->right, val, node->data);
    }
}
 
// Driver code
int main()
{
    struct Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    int node = 3;
 
    findParent(root, node, -1);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
 
/* A binary tree node has data, pointer
to left child and a pointer
to right child */
static class Node
{
    int data;
    Node left, right;
    Node(int data)
    {
        this.data = data;
        left = right = null;
    }
};
 
// Recursive function to find the
// parent of the given node
static void findParent(Node node,
                       int val, int parent)
{
    if (node == null)
        return;
 
    // If current node is the required node
    if (node.data == val)
    {
 
        // Print its parent
        System.out.print(parent);
    }
    else
    {
 
        // Recursive calls for the children
        // of the current node
        // Current node is now the new parent
        findParent(node.left, val, node.data);
        findParent(node.right, val, node.data);
    }
}
 
// Driver code
public static void main(String []args)
{
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    int node = 3;
 
    findParent(root, node, -1);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation of
# the above approach
 
''' A binary tree node has data, pointer
to left child and a pointer
to right child '''
class Node:
   
    def __init__(self, data):
       
        self.data = data
        self.left = None
        self.right = None
 
# Recursive function to find the
# parent of the given node
def findParent(node : Node,
               val : int,
               parent : int) -> None:
    if (node is None):
        return
 
    # If current node is
    # the required node
    if (node.data == val):
       
        # Print its parent
        print(parent)
    else:
       
        # Recursive calls
        # for the children
        # of the current node
        # Current node is now
        # the new parent
        findParent(node.left,
                   val, node.data)
        findParent(node.right,
                   val, node.data)
 
# Driver code
if __name__ == "__main__":
 
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    node = 3
    findParent(root, node, -1)
 
# This code is contributed by sanjeev2552


C#




// C# implementation of the approach
using System;
     
class GFG
{
 
/* A binary tree node has data, pointer
to left child and a pointer
to right child */
public class Node
{
    public int data;
    public Node left, right;
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
};
 
// Recursive function to find the
// parent of the given node
static void findParent(Node node,
                         int val, int parent)
{
    if (node == null)
        return;
 
    // If current node is the required node
    if (node.data == val)
    {
 
        // Print its parent
        Console.Write(parent);
    }
    else
    {
 
        // Recursive calls for the children
        // of the current node
        // Current node is now the new parent
        findParent(node.left, val, node.data);
        findParent(node.right, val, node.data);
    }
}
 
// Driver code
public static void Main(String []args)
{
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    int node = 3;
 
    findParent(root, node, -1);
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// JavaScript implementation of the approach
     
/* A binary tree node has data, pointer
to left child and a pointer
to right child */
class Node
{
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
 
// Recursive function to find the
// parent of the given node
function findParent(node, val, parent)
{
    if (node == null)
        return;
 
    // If current node is the required node
    if (node.data == val)
    {
 
        // Print its parent
        document.write(parent);
    }
    else
    {
 
        // Recursive calls for the children
        // of the current node
        // Current node is now the new parent
        findParent(node.left, val, node.data);
        findParent(node.right, val, node.data);
    }
}
 
// Driver code
var root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
var node = 3;
 
findParent(root, node, -1);
 
 
</script>


Output: 

1

 

Time Complexity: O(N).
Auxiliary Space: O(N). 



Similar Reads

Find parent of given node in a Binary Tree with given postorder traversal
Given two integers N and K where N denotes the height of a binary tree, the task is to find the parent of the node with value K in a binary tree whose postorder traversal is first [Tex]2^{N}-1 [/Tex] natural numbers [Tex](1, 2, ... 2^{N}-1) [/Tex] For N = 3, the Tree will be - 7 / \ 3 6 / \ / \ 1 2 4 5 Examples: Input: N = 4, K = 5 Output: 6 Explan
9 min read
Find the parent node of maximum product Siblings in given Binary Tree
Given a binary tree, the task is to find the node whose children have maximum Sibling product in the given Binary Tree. If there are multiple such nodes, return the node which has the maximum value. Examples: Input: Tree: 4 / \ 5 2 / \ 3 1 / \6 12Output: 3Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 an
16 min read
Find parent of each node in a tree for multiple queries
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.Examples: Tree: 0 / \ 1 2 | / \ 3 4 5 Input: N = 2 Output: 0 Explanation: Parent of
8 min read
Find Height of Binary Tree represented by Parent array
A given array represents a tree in such a way that the array value gives the parent node of that particular index. The value of the root node index would always be -1. Find the height of the tree. The height of a Binary Tree is the number of nodes on the path from the root to the deepest leaf node, and the number includes both root and leaf. Input:
13 min read
Find right sibling of a binary tree with parent pointers
Given a binary tree with parent pointers, find the right sibling of a given node(pointer to the node will be given), if it doesn’t exist return null. Do it in O(1) space and O(n) time? Examples: 1 / \ 2 3 / \ \ 4 6 5 / \ \ 7 9 8 / \ 10 12 Input : Given above tree with parent pointer and node 10 Output : 12 Recommended: Please solve it on PRACTICE f
10 min read
Construct Binary Tree from given Parent Array representation | Iterative Approach
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation
12 min read
Construct Binary Tree from given Parent Array representation
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation
27 min read
Maximum parent children sum in Binary tree
Given a Binary Tree, find the maximum sum in a binary tree by adding the parent with its children. Exactly three Node needs to be added. If the tree does not have a node with both of its children as not NULL, return 0. We simply traverse the tree and find the Node that has the maximum sum. We need to take care of the leaves. Implementation: C/C++ C
5 min read
Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
Given an integer X and a binary tree, the task is to count the number of triplet triplets of nodes such that their sum is greater than X and they have a grandparent -&gt; parent -&gt; child relationship. Example: Input: X = 100 10 / \ 1 22 / \ / \ 35 4 15 67 / \ / \ / \ / \ 57 38 9 10 110 312 131 414 / \ 8 39 Output: 6 The triplets are: 22 -&gt; 15
18 min read
Sum of all parent-child differences in a Binary Tree
Given a binary tree, find the sum of all parent-child differences for all the non-leaf nodes of the given binary tree. Note that parent-child difference is (parent node's value - (sum of child node's values)).Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output: -23 1st parent-child difference = 1 -(2 + 3) = -4 2nd parent-child difference = 2 -(4
7 min read