Ancestors in Binary Tree | Practice | GeeksforGeeks

Given a Binary Tree and a target key, you need to find all the ancestors of the given target key.
              1
            /   \
          2      3
        /  \
      4     5
     /
    7
Key: 7
Ancestor: 4 2 1
Example 1:
Input:
        1
      /   \
     2     3
target = 2
Output: 1

Example 2:
Input:
         1
       /   \
      2     3
    /  \   /  \
   4    5 6    8
  /
 7
target = 7
Output: 4 2 1

Your Task:
Your task is to complete the function Ancestors() that finds all the ancestors of the key in the given binary tree.
Note:
The return type is
cpp: vector
Java: ArrayList
python: list
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(H).
Note: H is the height of the tree and this space is used implicitly for the recursion stack.
Constraints:
1 ≤ N ≤ 103
1 ≤ data of node ≤ 104
0
adityagagtiwari3 weeks ago
Easy solution doston!!
 
class Solution
{
   
   public static ArrayList<Integer> Ancestors(Node root, int target)
   {
       // add your code here
       ArrayList<Integer> result = new ArrayList<>();
        getAncestors(root,target,result);
        return result;
   }
   //our method returns whether there exists a path to the target
   //if there exists a path to target then add the node to result and return true
   public static boolean getAncestors(Node root,int target,ArrayList<Integer> result)
   {
       if(root==null)
        return false;
        
       if(root.data==target)
       return true;
       //if the target exists in the left or right tree then return true after adding the node 
       //via which we are getting the target
        if(getAncestors(root.left,target,result)||getAncestors(root.right,target,result))
        {
            result.add(root.data);
            return true;
        }
        return false;
   }
}
0
tapanmanu20001 month ago
class Solution{
 public:
   // Function should return all the ancestor of the target node
   bool preorder(Node* root, int target, vector<int>& res){
       if(root == NULL) return false;
       if(root->data == target){
           return true;
       }
       res.push_back(root->data);
       bool l = preorder(root->left,target,res);
       if(l) return true;
       bool r = preorder(root->right,target,res);
       if(r) return true;
       res.pop_back();
       return false;
   }
   vector<int> Ancestors(struct Node *root, int target)
   {
       vector<int> res;
       if(root == NULL || root->data == target) return res;
       res.push_back(root->data);
       bool l = preorder(root->left, target, res);
       if(l) {
           reverse(res.begin(),res.end());
           return res;
       }
       bool r = preorder(root->right, target, res);
       if(r) {
           reverse(res.begin(), res.end());
           return res;
       }
       res.pop_back();
       return res;
   }
};
0
patildhiren442 months ago
// java sol
// 0.9 sec


class Solution
{
    
    static boolean util(Node root, int tar,ArrayList<Integer> al ){
        if(root==null){
            return false;
        }
        
        if(root.data==tar){
            return true;
        }
        
        if(util(root.left, tar, al) || util(root.right, tar, al)){
            al.add(root.data);
            return true;
        }
        return false;
    }
    
    public static ArrayList<Integer> Ancestors(Node root, int tar)
    {
        // add your code here
        ArrayList<Integer> al = new ArrayList<>();
        
        util(root, tar, al);
        return al;
    }
}
0
mohankumarit20012 months ago
class Solution{
  public:
    // Function should return all the ancestor of the target node
    bool found = false;
    void rec(Node* root,int target,stack<int> &res){
        if(found)return;
        if(!root)return;
         if(root->data==target){found =true;return;}
         res.push(root->data);
         rec(root->left,target,res);
         if(found)return;
         rec(root->right,target,res);
         if(found)return;
         res.pop();
    }
    vector<int> Ancestors(struct Node *root, int target)
    {
         // Code 
         vector<int> res;
         stack<int> q;
         rec(root,target,q);
         while(!q.empty()){res.push_back(q.top());q.pop();}
         return res;
        
    }
};
0
aryangarg19993 months ago
class Solution{
  public:
    // Function should return all the ancestor of the target node
    
    vector<int>ans ;
    
    Node *findAncestors(Node *node, int target)
    {
        if(node == nullptr)
         return nullptr ;
         
         if(node->left != nullptr)
         {
             if(node->left->data == target)   // Then this is the first ancestor (root)
             return node ;
         }
         
         
         if(node->right != nullptr)
         {
             if(node->right->data == target)
             return node ;
         }
         
         Node *left = findAncestors(node->left, target) ;
         Node *right = findAncestors(node->right, target) ;
         
         
         if(left)      // Means there is something returned in it.
         {
             ans.push_back(left->data) ;
             return node ;            // then the root of this left will be returned
         }
         
         
         if(right)
         {
             ans.push_back(right->data) ;
             return node ;
         }
         
    }
    
    vector<int> Ancestors(struct Node *root, int target)
    {
        ans.clear() ;
        Node *ret = findAncestors(root, target) ;
        ans.push_back(ret->data) ;
        return ans ;
    }
};
+1
codemohitprakanojia21033 months ago
ArrayList<Integer> Ancestors(Node root, int target)
    {
        // add your code here
        fun(root,target);
        return lis;
    }
    ArrayList<Integer> lis=new ArrayList<>();
    Stack<Integer> st=new Stack<>();
    
    void fun(Node root,int key){
        if(root==null) return;
        if(root.data!=key) st.push(root.data);
        else{
            while(!st.empty()){
                lis.add(st.pop());
            }
        }
        fun(root.left,key);
        fun(root.right,key);
        if(!st.empty())st.pop();
    }
+3
kronizerdeltac3 months ago
JAVA SOLUTION
 
public static boolean nodeToRootPath(Node root, int target, ArrayList<Integer> ans) {       if(root == null)           return false;
       if(root.data == target)           return true;
       boolean res = nodeToRootPath(root.left, target, ans) || nodeToRootPath(root.right, target, ans);       if(res)           ans.add(root.data);       return res;   }   public static ArrayList<Integer> Ancestors(Node root, int target) {       ArrayList<Integer> ans = new ArrayList<>();       nodeToRootPath(root, target, ans);       return ans;      }
+1
sohamdas86973 months ago
bool solve(Node* root, int target, vector <int>& v) 
    {
        if(root == NULL)
            return false;
        v.push_back(root->data);
        if(root->data == target)
            return true;
        bool lh = solve(root->left, target, v);
        bool rh = solve(root->right, target, v);
        if(lh || rh)
            return true;
        v.pop_back();
        return false;
    }
    // Function should return all the ancestor of the target node
    vector<int> Ancestors(struct Node *root, int target)
    {
        vector <int> v;
        bool l = solve(root, target, v);
        v.pop_back();
        reverse(v.begin(), v.end());
        return v;
    }
0
radheshyamnitj4 months ago
void helper(Node* root,int target, vector<int> &ans,bool &flag){
        
        if(!root) return;
        if(root->data==target){
           flag= true;
            return ;
        }
        if(!flag)
        helper(root->left,target,ans,flag);
        if(!flag)
        helper(root->right,target,ans,flag);
        
         if(flag==true){
            ans.push_back(root->data);
            return;
        }
    }
    vector<int> Ancestors(struct Node *root, int target)
    {
         vector<int>ans;
         bool flag;
         helper(root,target,ans,flag);
         return ans;
    }
0
mayurxxivk4 months ago
CorrectAnswer.🥇
Total Time Taken:0.9/2.3
 
    static boolean  pleaseHelp(Node root, int target , ArrayList<Integer>al)
    {
        
        if(root == null) return false;
        if(root.data == target) return true;
        
        if(pleaseHelp(root.left , target , al ) || pleaseHelp(root.right , target , al))
        {   
            al.add(root.data);
            return true;
        }
        return false;
        
    }
    public static ArrayList<Integer> Ancestors(Node root, int target)
     {
         ArrayList<Integer>al = new ArrayList<>();
         pleaseHelp(root ,target , al);
         return al;
     }
 
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.