Geeksforgeeks

Timer is Running

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.

```
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<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.

**Constraints:**

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.

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.

jainshubham52535 | 529 |

Pathak1899 | 436 |

yashdip123 | 380 |

kirtidee18 | 377 |

jots62 | 351 |

kirtidee18 | 1057 |

ykaushik | 752 |

aggarwalvatsal5 | 741 |

harbilassingh | 576 |

pmr_3689 | 570 |

blackshadows | 5456 |

Ibrahim Nash | 5450 |

akhayrutdinov | 5111 |

mb1973 | 4976 |

Quandray | 4827 |

Login to report an issue on this page.