K-th ancestor of a node in Binary Tree | Set 3

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, 2nd ancestor of node 4 and 5 is 1. 3rd ancestor of node 4 will be -1.

Tree_IMAGE



Approach: First we find the path of given key data from the root and we will store it into a vector then we simply return the kth index of the vector from the last.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Structure of Tree
struct node {
    node *left, *right;
    int data;
};
  
// To create a new node
node* newNode(int data)
{
    node* temp = new node;
    temp->left = temp->right = NULL;
    temp->data = data;
    return temp;
}
  
// Function to find the path from
// root to the target node
bool RootToNode(node* root, int key, vector<int>& v)
{
    if (root == NULL)
        return false;
  
    // Add current node to the path
    v.push_back(root->data);
  
    // If current node is the target node
    if (root->data == key)
        return true;
  
    // If the target node exists in
    // the left or the right sub-tree
    if (RootToNode(root->left, key, v)
        || RootToNode(root->right, key, v))
        return true;
  
    // Remove the last inserted node as
    // it is not a part of the path
    // from root to target
    v.pop_back();
    return false;
}
  
// Driver code
int main()
{
    struct node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
  
    // Given node
    int target = 4;
  
    // Vector to store the path from 
    // root to the given node
    vector<int> v;
  
    // Find the path from root to the target node
    RootToNode(root, target, v);
  
    int k = 2;
  
    // Print the Kth ancestor
    if (k > v.size() - 1 || k <= 0)
        cout << -1;
    else
        cout << v[v.size() - 1 - k];
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
  
# To create a  node 
class Node:
   
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
  
# Function to find the path 
# from root to the target node 
def RootToNode(root, key, v): 
   
    if root == None
        return False 
  
    # Add current node to the path 
    v.append(root.data) 
  
    # If current node is the target node 
    if root.data == key: 
        return True 
  
    # If the target node exists in 
    # the left or the right sub-tree 
    if (RootToNode(root.left, key, v) or
       RootToNode(root.right, key, v)):
        return True 
  
    # Remove the last inserted node 
    # as it is not a part of the 
    # path from root to target 
    v.pop() 
    return False 
   
# 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
    root.right.left = Node(6
    root.right.right = Node(7
  
    # Given node 
    target, k = 4, 2 
  
    # Vector to store the path 
    # from root to the given node 
    v = [] 
  
    # Find the path from root to the target node 
    RootToNode(root, target, v) 
  
    # Print the Kth ancestor 
    if k > len(v) - 1 or k <= 0
        print(-1
    else:
        print(v[len(v) - 1 - k]) 
  
# This code is contributed by Rituraj Jain

chevron_right


Output:

1


My Personal Notes arrow_drop_up

Love making project and exploring new things New to Competitive coding Do the newBelieve in yourself Love Parents

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.



Improved By : rituraj_jain



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.