Timer is Running

Ancestors in Binary Tree
Submissions: 23033   Accuracy:


  Difficulty: Easy   Marks: 2
Associated Course(s):   Amazon SDE Test Series

Given a Binary Tree and a target key, you need to find all the ancestors of the given target key.

            /   \
          2      3
        /  \
      4     5
Key: 7
Ancestor: 4 2 1

Example 1:

      /   \
     2     3
target = 2
Output: 1

Example 2:

       /   \
      2     3
    /  \   /  \
   4    5 6    8
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.
The return type is
cpp: vector<int>
Java: ArrayList<Integer>
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 recursion stack.

1 <= N <= 1000
1<= data of node <= 10000

Note: The Input/Output format and Examples given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Tanmay Agrawal
Author: harshitsidhwa

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.

to report an issue on this page.