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
Input: 1 / \ 2 3 target = 2 Output: 1
Input: 1 / \ 2 3 / \ / \ 4 5 6 8 / 7 target = 7 Output: 4 2 1
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
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.
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.