Kth Ancestor in a Tree | Practice | GeeksforGeeks

Given a binary tree of size  N, a node and a positive integer k., Your task is to complete the function kthAncestor(), the function should return the kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then return -1.

Example 1:


Input:
     K = 2
     Node = 4
Output: 1
Explanation:
Since, K is 2 and node is 4, so we
first need to locate the node and
look k times its ancestors.
Here in this Case node 4 has 1 as his
2nd Ancestor aka the Root of the tree.
 
Example 2:
Input:
k=1 
node=3
      1
    /   \
    2     3

Output:
1
Explanation:
K=1 and node=3 ,Kth ancestor of node 3 is 1.


Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
 
Constraints:
1<=N<=104
1<= K <= 100
0
mayank2000j1 month ago
bool isPossible(Node *root,int node, vector <Node*> &arr){   if(root==NULL)       return false;   arr.push_back(root);   if(root->data==node)       return true;   if(isPossible(root->left,node,arr) or isPossible(root->right,node,arr))       return true;   arr.pop_back();   return false;}int kthAncestor(Node *root, int k, int node){   // Code here   vector <Node*> arr;   if(isPossible(root,node,arr)){       // return arr[arr.size()-1-k]->data;       return k<arr.size() ? arr[arr.size()-1-k]->data : -1;   }   return -1;} 
0
akshaydoodwal1 month ago
Node* solve(Node* root,int &k,int node){
  // 1st base case
   if(root==NULL){       return NULL;      }   // 2nd base case   if(root->data==node){       return root;          }      Node* leftans=solve(root->left,k,node);   Node* rightans=solve(root->right,k,node);    if(leftans != NULL && rightans == NULL)   {       k--;       if(k <= 0)       {           k=INT_MAX;           return root;       }       return leftans;   }    if(leftans==NULL && rightans!=NULL){        k--;        if(k<=0){            k=INT_MAX;            return root;        }        else{            return rightans;        }            }    return NULL;}
int kthAncestor(Node *root, int k, int node){ Node* ans= solve(root,k,node); if(ans==NULL|| ans->data==node)    {        return -1;    }  else{     return ans->data; }}
+1
priyanshugupta1231232 months ago
EASY JAVA SOLUTION WITHOUT EXTRA SPACE:
 
class Tree
{
    int count =-1;
    int res = -1;
    public int kthAncestor(Node root, int k, int node)
    {
        utilFunc(root, k, node);
        return res;
    }
    
    public boolean utilFunc(Node root, int k, int node){
        if(root==null){
            return false;
        }
        if(root.data == node){
            count++;
            if(count==k){
                res = root.data;
            }
            return true;
        }
        boolean left = utilFunc(root.left , k , node);
        if(left){
            count++;
            if(count==k){
                res = root.data;
            }
            return true;
        }
        boolean right = utilFunc(root.right , k , node);
        if(right){
            count++;
            if(count==k){
                res = root.data;
            }
            return true;
        }
        return false;
    }
}
0
roysayantanblr992 months ago
class Tree{   int ans=0;   public int kthAncestor(Node root, int k, int node)   {       //Write your code here              ArrayList<Integer> al = new ArrayList<>();
       find_path(root,node,al,k);       //System.out.println(al);              return ans;          }      void find_path(Node root, int node, ArrayList<Integer> al, int k)   {       if(root!=null)       {           al.add(root.data);                      if(root.data == node)           {               //System.out.println(al);               int index= al.size()-1-k;                              if(index>=0 && index<=al.size()-1)               {                   ans= al.get(index);               }else{                   ans=-1;               }               return;
           }                                     find_path(root.left,node,al,k);           find_path(root.right,node,al,k);
           if(al.size()>0)           {               al.remove(al.size()-1);           }       }   }}
0
vishalja77192 months ago
Node* solve(Node*root,int &k,int node)
{
    if(root == NULL)
    {
        return NULL;
    }
    if(root->data == node)
    {
        return root;
    }
    Node* leftans=solve(root->left,k,node);
    Node* rightans=solve(root->right,k,node);
    
    if(leftans != NULL && rightans == NULL)
    {
        k--;
        if(k <= 0)
        {
            k=INT_MAX;
            return root;
        }
        return leftans;
    }
    if(leftans == NULL && rightans != NULL)
    {
        k--;
        if(k <= 0)
        {
            k=INT_MAX;
            return root;
        }
        return rightans;
    }
    
}
int kthAncestor(Node *root, int k, int node)
{
    // Code here
    Node* ans=solve(root,k,node);
    if(ans == NULL || ans->data == node)
    {
        return -1;
    }
    else{
        return ans->data;
    }
}
0
janvijindal052 months ago
Node* solve(Node *root, int &k, int node){   if(root==NULL)   return NULL;      if(root->data==node){       return root;   } Node* leftAns=solve(root->left,k,node);   Node* rightAns=solve(root->right,k,node);      if(leftAns!=NULL && rightAns==NULL){       k--;       if(k<=0){           k=INT_MAX;           return root;       } return leftAns;   } if(rightAns!=NULL && leftAns==NULL){       k--;       if(k<=0){           k=INT_MAX;           return root;       } return rightAns;} return NULL;
}
int kthAncestor(Node *root, int k, int node){   Node* ans=solve(root,k,node);   if(ans==NULL || ans->data==node)   return -1;   else   return ans->data;} 
0
sangamchoudhary72 months ago
int solve(Node* root,int k,int node,int &ans){
    if(!root) return 0;
    else if(root->data == node) return 1;
    
    int ld = solve(root->left,k,node,ans); 
    int rd = solve(root->right,k,node,ans); 
    
    if(ld == k or rd == k){
        ans = root->data; 
        return ans;
    }
    
    if(ld) return ld+1;
    else if(rd) return rd+1;
    
    return 0;
}

int kthAncestor(Node *root, int k, int node){
    int ans = -1;
    solve(root,k,node,ans);
    return ans;
}
0
bidishapandit032 months ago
//Java BFS solution
public void generateAncestor(Node root,HashMap<Integer,Integer>anc)
    {
        anc.put(root.data,-1);
        Queue<Node> q=new LinkedList<>();
        q.add(root);
        while(!q.isEmpty())
        {
            Node curr=q.poll();
            if(curr.left!=null)
            {
        anc.put(curr.left.data,curr.data);
                q.add(curr.left);
            }
            if(curr.right!=null)
            {
           anc.put(curr.right.data,curr.data);
                q.add(curr.right);
            }
        }
    }
    public int kthAncestor(Node root, int k, int node)
    {
        //Write your code here
       
        HashMap<Integer,Integer>anc=new HashMap<>();
        generateAncestor(root,anc);
        while(k>0&&node!=-1)
        {
            node=anc.get(node);
            k--;
            
        }
        return node;
    }
0
dipsaili20193 months ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
struct Node{   int data;   struct Node *left;   struct Node *right;};Node* newNode(int val){   Node* temp = new Node;   temp->data = val;   temp->left = NULL;   temp->right = NULL;      return temp;}Node* buildTree(string str){      // Corner Case   if(str.length() == 0 || str[0] == 'N')           return NULL;      // Creating vector of strings from input    // string after spliting by space   vector<string> ip;      istringstream iss(str);   for(string str; iss >> str; )       ip.push_back(str);          // Create the root of the tree   Node* root = newNode(stoi(ip[0]));          // Push the root to the queue   queue<Node*> queue;   queue.push(root);          // Starting from the second element   int i = 1;   while(!queue.empty() && i < ip.size()) {                  // Get and remove the front of the queue       Node* currNode = queue.front();       queue.pop();                  // Get the current node's value from the string       string currVal = ip[i];                  // If the left child is not null       if(currVal != "N") {                          // Create the left child for the current node           currNode->left = newNode(stoi(currVal));                          // Push it to the queue           queue.push(currNode->left);       }                  // For the right child       i++;       if(i >= ip.size())           break;       currVal = ip[i];                  // If the right child is not null       if(currVal != "N") {                          // Create the right child for the current node           currNode->right = newNode(stoi(currVal));                          // Push it to the queue           queue.push(currNode->right);       }       i++;   }      return root;}int kthAncestor(Node *root, int k, int node);
int main(){   int t;scanf("%d ",&t);   while(t--)   {       int k , node;       scanf("%d ",&k);       scanf("%d ",&node);       string s; getline(cin,s); Node* root = buildTree(s); cout<<kthAncestor(root,k,node)<<endl;   }   return 0;}// } Driver Code Ends
//User function Template for C++/*Structure of the node of the binary tree is asstruct Node{int data;struct Node *left, *right;};*/// your task is to complete this functionNode* n;int ans = -1;void pmp(Node *root, unordered_map<Node*, Node*> &mp, int node){   queue<Node*> q;   q.push(root);   while(!q.empty()){       root = q.front();       if(root->data == node) n = root;       q.pop();       if(root->left){           mp[root->left] = root;           q.push(root->left);       }       if(root->right){           mp[root->right] = root;           q.push(root->right);       }   }}void upr(Node* n,  unordered_map<Node*, Node*> &mp, int k){   if(k == 0){       //cout<<n->data;       ans = n->data;       return;   }   if(mp[n] == NULL) return;   upr(mp[n], mp, k-1);} int kthAncestor(Node *root, int k, int node){   unordered_map<Node*, Node*>mp;   pmp(root, mp, node);   upr(n, mp, k);   return ans;} 
+6
sangamchoudhary74 months ago
2 Approach
 
Time - O(n) , Space - O(n + h + h) where h → height of tree
Time - O(n) , Space - O(n + h + h) where h → height of tree
vector<int> ans;
void nodeToroot(Node* root,int node,vector<int> temp){
    if(!root) return;
    if(root->data == node){
        ans = temp;
        return;
    }
    temp.push_back(root->data);
    nodeToroot(root->left,node,temp);
    nodeToroot(root->right,node,temp);
    temp.pop_back();
}

int kthAncestor(Node *root, int k, int node){
    vector<int> temp;
    nodeToroot(root,node,temp);
    if(ans.empty()) return -1;
    else if(ans.size() < k) return -1;
    return ans[ans.size() - k];
}
2. Time - O(n) , Space - O(n)
 
int dfs(Node* root,int node,int k,int &ans){
    if(!root) return 0;
    if(root->data == node) return 1;
    
    int lf = dfs(root->left,node,k,ans);
    int rf = dfs(root->right,node,k,ans);
    
    if(lf == k or rf == k){
        ans = root->data;
    }
    
    if(lf) return lf+1;
    else if(rf) return rf+1;
    else return 0;
}

int kthAncestor(Node *root, int k, int node){
    int ans = -1;
    dfs(root,node,k,ans);
    return ans;
}
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.