Open In App

Kth ancestor of a node in binary tree | Set 2

Last Updated : 31 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 the kth ancestor. Once we have reached the kth parent, we will simply print the node and return NULL. 

Below is the implementation of the above idea: 

C++
/* C++ program to calculate Kth ancestor of given node */
#include <bits/stdc++.h>
using namespace std;

// A Binary Tree Node
struct Node
{
    int data;
    struct Node *left, *right;
};

// temporary node to keep track of Node returned
// from previous recursive call during backtrack
Node* temp = NULL;

// recursive function to calculate Kth ancestor
Node* 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 node
Node* newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}

// Driver program to test above functions
int 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
// Java program to calculate Kth ancestor of given node 
public class Solution
{

// A Binary Tree Node
static class Node
{
    int data;
    Node left, right;
};

// temporary node to keep track of Node returned
// from previous recursive call during backtrack
static Node temp = null;
static int k;

// recursive function to calculate Kth ancestor
static 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 node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}

// Driver code
public 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
Python
# Python program to calculate the
# ancestor of given node

# A Binary Tree Node 
class 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 ancestor 
def 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
        
        elif (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 Code
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 YASH AGARWAL(yashagarwal2852002)
C#
using System;

public class Node
{
    public int Data;
    public Node Left, Right;
    public Node(int data)
    {
        Data = data;
        Left = Right = null;
    }
}

public class BinaryTree
{
    private static Node temp = null;

    public static Node KthAncestorDFS(Node root, int node, ref int k)
    {
        // Base case
        if (root == null)
            return null;

        if (root.Data == node ||
            (temp = KthAncestorDFS(root.Left, node, ref k)) != null ||
            (temp = KthAncestorDFS(root.Right, node, ref k)) != null)
        {
            if (k > 0)
                k--;
            else if (k == 0)
            {
                // Print the kth ancestor
                Console.WriteLine("Kth ancestor is: " + root.Data);

                // Return null to stop further backtracking
                return null;
            }

            // Return current node to previous call
            return root;
        }

        return null;
    }

    public static void Main()
    {
        // Let us create binary tree shown in above diagram
        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 k = 2;
        int node = 5;

        // Print kth ancestor of given node
        Node parent = KthAncestorDFS(root, node, ref k);

        // Check if parent is not NULL, it means
        // there is no Kth ancestor of the node
        if (parent != null)
            Console.WriteLine("-1");
    }
}
JavaScript
class Node {
    constructor(data) {
        this.data = data;
        this.left = this.right = null;
    }
}

let temp = null;

function kthAncestorDFS(root, node, k) {
    // Base case
    if (root == null)
        return null;

    if (root.data === node ||
        (temp = kthAncestorDFS(root.left, node, k)) !== null ||
        (temp = kthAncestorDFS(root.right, node, k)) !== null) {
        if (k.value > 0)
            k.value--;
        else if (k.value === 0) {
            // Print the kth ancestor
            console.log("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 node
function newNode(data) {
    return new Node(data);
}

// Driver program to test above functions
function main() {
    // Let us create binary tree shown in above diagram
    const root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);

    let k = { value: 2 };
    const node = 5;

    // Print kth ancestor of given node
    const parent = kthAncestorDFS(root, node, k);

    // Check if parent is not NULL, it means
    // there is no Kth ancestor of the node
    if (parent !== null)
        console.log("-1");
}

main();

Output
Kth ancestor is: 1

Time Complexity: O(n), where n is the number of nodes in the binary tree. 

Auxiliary Space: O(h) where h is the height of binary tree due to recursion call.

   


Next Article
Article Tags :
Practice Tags :

Similar Reads