Kth ancestor of a node in binary tree | Set 2 - GeeksforGeeks

21 Mar, 2022
Given a binary tree in which nodes are numbered from 1 to n. Given a node and a positive integer K. We have to print the Kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.For example in the below given binary tree, the 2nd ancestor of 5 is 1. 3rd ancestor of node 5 will be -1.  
 
We have discussed a BFS based solution for this problem in our previous article. If you observe that solution carefully, you will see that the basic approach was to first find the node and then backtrack to the kth parent. The same thing can be done using recursive DFS without using an extra array. The idea of using DFS is to first find the given node in the tree and then backtrack k times to reach to the kth ancestor, once we have reached the kth parent, we will simply print the node and return NULL. Below is the implementation of above idea:  
C++
Java
Python3
C#
Javascript
/* C++ program to calculate Kth ancestor of given node */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{    int data;    struct Node *left, *right;}; // temporary node to keep track of Node returned// from previous recursive call during backtrackNode* temp = NULL; // recursive function to calculate Kth ancestorNode* kthAncestorDFS(Node *root, int node , int &k){      // Base case    if (!root)        return NULL;         if (root->data == node||       (temp =  kthAncestorDFS(root->left,node,k)) ||       (temp =  kthAncestorDFS(root->right,node,k)))    {          if (k > 0)                   k--;                 else if (k == 0)        {            // print the kth ancestor            cout<<"Kth ancestor is: "<<root->data;                         // return NULL to stop further backtracking            return NULL;        }                 // return current node to previous call        return root;    }} // Utility function to create a new tree nodeNode* newNode(int data){    Node *temp = new Node;    temp->data = data;    temp->left = temp->right = NULL;    return temp;} // Driver program to test above functionsint main(){    // Let us create binary tree shown in above diagram    Node *root = newNode(1);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->left->right = newNode(5);     int k = 2;    int node = 5;     // print kth ancestor of given node    Node* parent = kthAncestorDFS(root,node,k);         // check if parent is not NULL, it means    // there is no Kth ancestor of the node    if (parent)        cout << "-1";         return 0;}
// Java program to calculate Kth ancestor of given nodeclass Solution{ // A Binary Tree Nodestatic class Node{    int data;    Node left, right;}; // temporary node to keep track of Node returned// from previous recursive call during backtrackstatic Node temp = null;static int k; // recursive function to calculate Kth ancestorstatic Node kthAncestorDFS(Node root, int node ){    // Base case    if (root == null)        return null;         if (root.data == node||    (temp = kthAncestorDFS(root.left,node)) != null ||    (temp = kthAncestorDFS(root.right,node)) != null)    {        if (k > 0)                k--;                 else if (k == 0)        {            // print the kth ancestor            System.out.print("Kth ancestor is: "+root.data);                         // return null to stop further backtracking            return null;        }                 // return current node to previous call        return root;    }    return null;} // Utility function to create a new tree nodestatic Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} // Driver codepublic static void main(String args[]){    // Let us create binary tree shown in above diagram    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);     k = 2;    int node = 5;     // print kth ancestor of given node    Node parent = kthAncestorDFS(root,node);         // check if parent is not null, it means    // there is no Kth ancestor of the node    if (parent != null)        System.out.println("-1");}} // This code is contributed by Arnab Kundu
""" Python3 program to calculate Kth    ancestor of given node """ # A Binary Tree Node# Utility function to create a new tree nodeclass newNode:     # Constructor to create a new node    def __init__(self, data):        self.data = data        self.left = None        self.right = None # recursive function to calculate# Kth ancestordef kthAncestorDFS(root, node, k):         # Base case    if (not root):        return None         if (root.data == node or       (kthAncestorDFS(root.left, node, k)) or       (kthAncestorDFS(root.right, node, k))):                 if (k[0] > 0):            k[0] -= 1                 else if (k[0] == 0):                         # print the kth ancestor            print("Kth ancestor is:", root.data)                         # return None to stop further            # backtracking            return None                     # return current node to previous call        return root     # Driver Codeif __name__ == '__main__':    root = newNode(1)    root.left = newNode(2)    root.right = newNode(3)    root.left.left = newNode(4)    root.left.right = newNode(5)     k = [2]    node = 5     # print kth ancestor of given node    parent = kthAncestorDFS(root,node,k)         # check if parent is not None, it means    # there is no Kth ancestor of the node    if (parent):        print("-1") # This code is contributed# by SHUBHAMSINGH10
// C# program to calculate Kth ancestor of given nodeusing System;     class GFG{ // A Binary Tree Nodepublic class Node{    public int data;    public Node left, right;}; // temporary node to keep track of Node returned// from previous recursive call during backtrackstatic Node temp = null;static int k; // recursive function to calculate Kth ancestorstatic Node kthAncestorDFS(Node root, int node ){    // Base case    if (root == null)        return null;         if (root.data == node||    (temp = kthAncestorDFS(root.left,node)) != null ||    (temp = kthAncestorDFS(root.right,node)) != null)    {        if (k > 0)                k--;                 else if (k == 0)        {            // print the kth ancestor            Console.Write("Kth ancestor is: "+root.data);                         // return null to stop further backtracking            return null;        }                 // return current node to previous call        return root;    }    return null;} // Utility function to create a new tree nodestatic Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} // Driver codepublic static void Main(String []args){    // Let us create binary tree shown in above diagram    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);     k = 2;    int node = 5;     // print kth ancestor of given node    Node parent = kthAncestorDFS(root,node);         // check if parent is not null, it means    // there is no Kth ancestor of the node    if (parent != null)        Console.WriteLine("-1");}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to calculate Kth// ancestor of given node // A Binary Tree Nodeclass Node{    constructor()    {        this.data = 0;        this.left = null;        this.right = null;    }}; // temporary node to keep track of Node returned// from previous recursive call during backtrackvar temp = null;var k = 0; // recursive function to calculate Kth ancestorfunction kthAncestorDFS(root, node ){    // Base case    if (root == null)        return null;         if (root.data == node||    (temp = kthAncestorDFS(root.left,node)) != null ||    (temp = kthAncestorDFS(root.right,node)) != null)    {        if (k > 0)                k--;                 else if (k == 0)        {            // print the kth ancestor            document.write("Kth ancestor is: "+root.data);                         // return null to stop further backtracking            return null;        }                 // return current node to previous call        return root;    }    return null;} // Utility function to create a new tree nodefunction newNode(data){    var temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} // Driver code// Let us create binary tree shown in above diagramvar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);k = 2;var node = 5;// print kth ancestor of given nodevar parent = kthAncestorDFS(root,node); // check if parent is not null, it means// there is no Kth ancestor of the nodeif (parent != null)    document.write("-1");   </script>
Output:  
Kth ancestor is: 1
Time Complexity: O(n), where n is the number of nodes in the binary tree.  
YouTubeGeeksforGeeks501K subscribersKth ancestor of a node in binary tree | Set 2 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=HeY99dtGi6U" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
SHUBHAMSINGH10
andrew1234
29AjayKumar
nidhi_biet
rutvik_56
mathuriarajatkumar
surinderdawra388
simmytarika5
Binary Tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
A program to check if a binary tree is BST or not